package cn.hhj.disovery.impl; import cn.hhj.balance.LoadBalanceStrategy; import cn.hhj.balance.RandomLoadBalance; import cn.hhj.config.ZkConfig; import cn.hhj.disovery.IServiceDiscovery; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.recipes.cache.PathChildrenCache; import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener; import org.apache.curator.retry.ExponentialBackoffRetry; import java.util.ArrayList; import java.util.List; public class ServiceDiscoveryWithZk implements IServiceDiscovery { private CuratorFramework curatorFramework =null; List serviceRepos=new ArrayList<>(); //服务地址的本地缓存 { //初始化zookeeper的连接, 会话超时时间是5s,衰减重试 curatorFramework = CuratorFrameworkFactory.builder(). connectString(ZkConfig.CONNECTION_STR).sessionTimeoutMs(5000). retryPolicy(new ExponentialBackoffRetry(1000, 3)). namespace("registry") .build(); curatorFramework.start(); } @Override public List discovery(String serviceName) { String path="/"+serviceName; if(serviceRepos.isEmpty()) { try { serviceRepos = curatorFramework.getChildren().forPath(path); registryWatch(path); } catch (Exception e) { e.printStackTrace(); } } return serviceRepos; } private void registryWatch(String path) throws Exception { PathChildrenCache nodeCache=new PathChildrenCache(curatorFramework,path,true); PathChildrenCacheListener cacheListener=(curatorFramework1, pathChildrenCacheEvent)->{ System.out.println("客户端收到变更节点的事件"); serviceRepos=curatorFramework1.getChildren().forPath(path); }; nodeCache.getListenable().addListener(cacheListener); nodeCache.start(); } }