1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253 |
- 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<String> 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<String> 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();
- }
- }
|