1声明zookeeper的远程坐标
2. 声明远程接口 继承Remote 在里面声明方法
3. 声明远程调用该方法(impl)继承UnicastRempteObject 实现service接口
4. 发布远程服务
5.发布远程服务的方法 (动态获取参数)(
4.1声明端口号
4.2声明url地址
4.3绑定(URL地址和远程对象)
4.4.服务注册(创建服务方法封装))
6.创建服务注册方法
6.1获取zookeeper对象
6.2将url转化为byte数组
6.2将url地址信息存储到zookeeper中创建zk节点 他的节点为顺序和瞬时节点其中provider节点为物理节点
7.创建zookeeper对象方法
7.01声明对象
7.1创建zookeeper对象
7.11判断zk对象是否判断成功
7.111唤醒主线程
7.2 让主线程睡觉
7.3返回zookeeper对象
public class TestProviderZk {
public static void main(String[] args) throws IOException, InterruptedException, AlreadyBoundException, KeeperException {
//发布远程服务
publisher(8888,"localhost",new ProviderZkServiceImpl());
System.out.println("端口号7777的远程服务发布成功");
}
//创建发布远程服务的方法
private static void publisher(int port, String host, Remote remote) throws IOException, AlreadyBoundException, KeeperException, InterruptedException {
//服务发布
//声明端口号
LocateRegistry.createRegistry(port);
//声明url地址
String url = "rmi://"+host+":"+port+"/rmi";
//绑定
Naming.bind(url,remote);
//服务注册
writeUrl(url);
}
//创建服务注册方法
private static void writeUrl(String url) throws KeeperException, InterruptedException, IOException {
//获得zookeeper对象
ZooKeeper zk= connectionZK();
//将url地址信息转化为字节数组
byte[] bytes = url.getBytes();
//将url地址信息存储到zookeeper中 zk节点为顺序和瞬时节点,其中provider节点为物理节点
zk.create(Constant.ZK_SERVICE,bytes, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
}
//实现线程同步
private static CountDownLatch latch = new CountDownLatch(1);
//创建zookeeper对象
private static ZooKeeper connectionZK() throws IOException, InterruptedException {
//声明对象
ZooKeeper zk = null;
zk = new ZooKeeper(Constant.ZK_HOST, Constant.ZK_TIME_OUT, new Watcher() {
@Override
public void process(WatchedEvent event) {
//判断zk对象是否创建成功
if(event.getState()==Event.KeeperState.SyncConnected){
//唤醒主线程
latch.countDown();//唤醒休眠线程
}
}
});
//让主线程休眠
latch.await();
//返回zookeeper对象
return zk;
}
}
public interface Constant {
//声明zookeeper地址
String ZK_HOST="192.168.154.131:2181,192.168.154.131:2182,192.168.154.131:2183";
//链接超时时间
int ZK_TIME_OUT=5000;
//物理节点,永久节点
String ZK_REGISTER="/provider";
//保存服务地址的瞬间节点
String ZK_SERVICE=ZK_REGISTER+"/service";
}