RegistryCenterWithZk.java 1.4 KB

1234567891011121314151617181920212223242526272829303132333435
  1. package cn.hhj.regiest;
  2. import cn.hhj.config.ZkConfig;
  3. import org.apache.curator.framework.CuratorFramework;
  4. import org.apache.curator.framework.CuratorFrameworkFactory;
  5. import org.apache.curator.retry.ExponentialBackoffRetry;
  6. import org.apache.zookeeper.CreateMode;
  7. public class RegistryCenterWithZk implements IRegistryCenter {
  8. private CuratorFramework curatorFramework = null;
  9. {
  10. //初始化zookeeper的连接, 会话超时时间是5s,衰减重试
  11. curatorFramework = CuratorFrameworkFactory.builder().
  12. connectString(ZkConfig.CONNECTION_STR).sessionTimeoutMs(5000).
  13. retryPolicy(new ExponentialBackoffRetry(1000, 3)).
  14. namespace("registry")
  15. .build();
  16. curatorFramework.start();
  17. }
  18. @Override
  19. public void registry(String serviceName, String serviceAddress) {
  20. String servicePath = "/" + serviceName;
  21. try{
  22. // 判断节点是否存在
  23. if (curatorFramework.checkExists().forPath(servicePath)==null){
  24. curatorFramework.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath(servicePath);
  25. }
  26. String addressPath=servicePath+"/"+serviceAddress;
  27. String result=curatorFramework.create().withMode(CreateMode.EPHEMERAL).forPath(addressPath);
  28. System.out.println("服务注册成功:"+result);
  29. }catch (Exception e){e.printStackTrace();}
  30. }
  31. }