Java 基于 org.mousio.etcd4j 服务注册与发现最简demo

java 基于 org.mousio.etcd4j 服务注册与发现

  1. maven 依赖

        <dependency>
            <groupId>org.mousio</groupId>
            <artifactId>etcd4j</artifactId>
            <version>2.15.0</version>
        </dependency>
        
        <!-- json 处理 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.62</version>
       </dependency>

构建java基类

import java.util.List;
/**
 * 注册的一个服务
 */
public class EtcdNodeService {

    private String heartbeatTime;

    private String name;

    private String startTime;

    private List<EtcdNode> nodes;
    
	/** 省略 get set 方法 */
}

/**
 * etcd 结点元数据
 */
public class EtcdNode {

    //ip地址
    private String ipAddress;
    //结点唯一标识
    private String id;
    //端口号
    private int port;
    
	/** 省略 get set 方法 */
}

服务注册

//服务注册
        URI[] uris = new URI[3];
        uris[0] = URI.create("http://etcd1.com:6003");
        uris[1] = URI.create("http://etcd2.com:6003");
        uris[2] = URI.create("http://etcd3.com:6003");
        
        String serviceName = "register-test-key";
        String ipAddr = "192.168.101.3";
        int port = 3333;
        String nodeId = UUID.randomUUID().toString().replaceAll("-","");
        String etcdKey = "/services/" + serviceName + "/" + nodeId;
        
        EtcdClient etcdClient = new EtcdClient(uris);
        EtcdNodeService etcdNodeService = new EtcdNodeService();
        etcdNodeService.setHeartbeatTime(dataFormate(new Date()));
        etcdNodeService.setName(serviceName);
        etcdNodeService.setStartTime(dataFormate(new Date()));
        List<EtcdNode> nodes = new ArrayList<>();
        EtcdNode etcdNode = new EtcdNode();
        etcdNode.setIpAddress(ipAddr);
        etcdNode.setId(nodeId);
        etcdNode.setPort(port);
        nodes.add(etcdNode);
        etcdNodeService.setNodes(nodes);
        
        //注册结点
        try {
        	//get 保证立即执行
            etcdClient.put(etcdKey, JSON.toJSONString(etcdNodeService)).ttl(60).send().get();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        //死循环模拟 心跳 保活
        while (true){
            try {
                Thread.sleep(20* 1000L);
                System.out.println("休眠结束");
                etcdClient.refresh(etcdKey, 60).send();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

服务发现

    public void discovery_test() throws IOException, EtcdAuthenticationException, TimeoutException, EtcdException {

        URI[] uris = new URI[3];
        uris[0] = URI.create("http://etcd1.com:6003");
        uris[1] = URI.create("http://etcd2.com:6003");
        uris[2] = URI.create("http://etcd3.com:6003");
        String serviceName = "register-test-key";
        String etcdNodeKey = "/services/" + serviceName;

        EtcdClient etcdClient = new EtcdClient(uris);
        System.out.println("etcd version server => " + etcdClient.version().getServer());
        System.out.println("etcd version getCluster => " + etcdClient.version().getCluster());
        EtcdKeyGetRequest etcdKeyGetRequest1 = etcdClient.get(etcdNodeKey);
        //获取结点信息
        EtcdKeysResponse etcdKeysResponse1 = etcdKeyGetRequest1.send().get();
        List<EtcdKeysResponse.EtcdNode> nodes = etcdKeysResponse1.node.nodes;
        Map<String,Set<String>> keyAndAddr = new HashMap<>();
        for (EtcdKeysResponse.EtcdNode node : nodes) {
            EtcdNodeService etcdNodeService = JSON.parseObject(node.getValue(), EtcdNodeService.class);
            List<EtcdNode> nodes1 = etcdNodeService.getNodes();
            String name = etcdNodeService.getName();

            if(StringUtils.isEmpty(name)){
                System.out.println("错误 name");
                return;
            }
            if(!CollectionUtils.isEmpty(nodes1)){
                nodes1.forEach(etcdNode -> {
                    Set<String> strings = keyAndAddr.get(name);
                    if(CollectionUtils.isEmpty(strings)){
                        strings = new HashSet<>();
                        strings.add(etcdNode.getIpAddress() + ":" + etcdNode.getPort());
                        keyAndAddr.put(name,strings);
                    }else {
                        strings.add(etcdNode.getIpAddress() + ":" + etcdNode.getPort());
                    }
                });
            }

            System.out.println( "creIndex => " + node.getCreatedIndex());
            System.out.println( "modiIndex => " + node.getModifiedIndex());
            System.out.println( "key => " + node.getKey());
            System.out.println( "nodes => " + node.getNodes());
            System.out.println( "value => " + node.getValue());
            System.out.println( "expira => " + node.getExpiration());
            System.out.println( "ttl => " + node.getTTL());
            System.out.println( "isdir => " + node.dir);
        }
        System.out.println(keyAndAddr);
    }
//控制台输出
20:41:09.582 [nioEventLoopGroup-2-3] DEBUG mousio.etcd4j.transport.EtcdResponseHandler - Received 200 for GET /v2/keys/services/register-test-key
20:41:09.619 [nioEventLoopGroup-2-3] DEBUG mousio.etcd4j.transport.EtcdNettyClient - Connection closed for request GET on uri /v2/keys/services/register-test-key 
creIndex => 818568982
modiIndex => 818570628
key => /services/register-test-key/709b0357438b4183a7d6d97197d874fa
nodes => []
value => {"heartbeatTime":"2020-01-11 20:40:30","name":"register-test-key","nodes":[{"id":"709b0357438b4183a7d6d97197d874fa","ipAddress":"192.168.101.3","port":3333}],"startTime":"2020-01-11 20:40:30"}
expira => Sat Jan 11 20:41:50 CST 2020
ttl => 42
isdir => false
{register-test-key=[192.168.101.3:3333]}

总结

  1. etcd 是一个高可用分布式键值存储方案,内部基于raft协议所为一致性算法,因此 etcd 只满足CAP中的CP,没有满足A。
  2. etcd 是一个轻量级的简单,安全,高效的注册中心。
  3. 安装,使用,配置,和运维都相对简单。
©️2020 CSDN 皮肤主题: 书香水墨 设计师:CSDN官方博客 返回首页