以下是我的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
方法,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;
}
}
通常,这不是策展人问题或动物园管理员问题。这基本上是一个设计问题,我试图了解我的操作方式是否会出现问题?而且我假设CuratorFramework
也会是线程安全的吗?
是的,您可以static
从其他类中调用方法。
您的签名如下所示:
protected static List<String> getChildren(String node) throws Exception
之所以不能从另一个类中调用它,是因为它protected
(对当前类和子类public
可见)而不是(对任何地方都可见)。
如果使其可见,则可以使用进行调用CuratorClient.getChildren()
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句