以下是我的CuratorClient
课程,它连接到Zookeeper并开始领导者选举过程。
public class CuratorClient {
// can I make this as static?
private static CuratorFramework client;
private String latchPath;
private String id;
private LeaderLatch leaderLatch;
public CuratorClient(String connString, String latchPath, String id) {
client = CuratorFrameworkFactory.newClient(connString, new ExponentialBackoffRetry(1000, Integer.MAX_VALUE));
this.id = id;
this.latchPath = latchPath;
}
public void start() throws Exception {
client.start();
client.getCuratorClient().blockUntilConnectedOrTimedOut();
leaderLatch = new LeaderLatch(client, latchPath, id);
leaderLatch.start();
}
public boolean isLeader() {
return leaderLatch.hasLeadership();
}
public Participant currentLeader() throws Exception {
return leaderLatch.getLeader();
}
public void close() throws IOException {
leaderLatch.close();
client.close();
}
// can I use below method from any other class ?
protected static List<String> getChildren(String node) throws Exception {
return client.getChildren().forPath(node);
}
}
当我的服务启动时,在静态块中我使用CuratorClient建立与Zookeeper的连接并启动领导者选举过程。
public class TestService {
private static CuratorClient curatorClient = null;
static {
try {
String connectionString = "some-string";
String hostname = "machineA";
curatorClient = new CuratorClient(connectionString, "/my/latch", hostname);
curatorClient.start();
} catch (Exception ex) {
// log exception
}
}
....
....
// some method
public Map<String, String> installNewSoftware(String node) {
//.. some other code
try {
List<String> children = CuratorClient.getChildren("/my/example");
System.out.println(children);
} catch (Exception e) {
e.printStackTrace();
}
//.. some other code
return null;
}
}
现在我还有一些其他类喜欢使用getChildren
的{{1}}方法,所以在这个课程中,我可以直接使用这个CuratorClient
正确吗?
CuratorClient.getChildren("/my/example");
一般来说,这不是策展人问题或动物园管理员问题。这基本上是一个设计问题,我试图了解我这样做是否会有任何问题?我假设public class DifferentClass {
....
....
// some new method
public Map<String, String> installNewSoftware(String node) {
try {
List<String> children = CuratorClient.getChildren("/my/example");
System.out.println(children);
} catch (Exception e) {
e.printStackTrace();
}
//.. some other code
return null;
}
}
也是线程安全的吗?
答案 0 :(得分:2)
是的,您可以从其他类调用static
方法。
您的签名如下:
protected static List<String> getChildren(String node) throws Exception
你不能从另一个类调用它的原因是因为它是protected
(对当前类和子类可见)而不是public
(对任何地方都可见)。
如果您看到它,可以使用CuratorClient.getChildren()
来调用它。
More information on access modifiers。
More information on class members (static
fields)