rmi 服务支持
rmi 服务端注册服务
public class HelloServiceImpl extends UnicastRemoteObject implements HelloService
int port = 1099;
String url = "rmi://192.168.11.131:1099/demo.zookeeper.remoting.server.HelloServiceImpl";
LocateRegistry.createRegistry(port);
Naming.rebind(url, new HelloServiceImpl()); // 注册一个服务端的service
rmi 客户端调用服务
public interface HelloService extends Remote
String url = "rmi://192.168.11.131:1099/demo.zookeeper.remoting.server.HelloServiceImpl";
HelloService helloService = (HelloService) Naming.lookup(url);
String result = helloService.sayHello("Jack");
System.out.println(result); // 打印服务端返回的内容
public interface Constant {
String ZK_CONNECTION_STRING = "127.0.0.1:2181";
int ZK_SESSION_TIMEOUT = 5000;
String ZK_REGISTRY_PATH = "/registry";
String ZK_PROVIDER_PATH = ZK_REGISTRY_PATH + "/provider";
}
zookeeper 服务
ZooKeeper zk = new ZooKeeper(Constant.ZK_CONNECTION_STRING, Constant.ZK_SESSION_TIMEOUT, new Watcher() { // 连接 ZooKeeper 服务器并获取 ZooKeeper 对象
@Override
public void process(WatchedEvent event) {
// 执行节点变化
}
});
// 创建节点
if (zk != null) {
byte[] data = new byte[1024]; // 节点内容
String path = zk.create(Constant.ZK_PROVIDER_PATH, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL); // 创建一个临时性且有序的 ZNode
}
// 获取 ZK_REGISTRY_PATH 子节点的节点名称 并且对此监控 ,但是监控只能生效一次
List<String> nodeList = zk.getChildren(Constant.ZK_REGISTRY_PATH, new Watcher() {
@Override
public void process(WatchedEvent event) {
if (event.getType() == Event.EventType.NodeChildrenChanged) {
// 若子节点有变化,则重新调用该方法(为了获取最新子节点中的数据)
}
}
});
zk.getData(“/register/provider”, false, null); // 获取该节点的内容