自定义服务的服务注册- zookeeper
服务注册使用 zookeeper 的大致过程如下
- 链接 zookeeper 集群或者单机
- 注册自己的 ip + 端口到 zookeeper 的 node(这个 node 要是临时节点的,因为可以保证健康检查以及服务发现的高可用
编码实现
package com.rpc.custom_rpc.registery;
import com.rpc.custom_rpc.config.CustomRpcConfig;
import com.rpc.pre.zookeeper.curator.ZkCuratorFrameworkServerOps;
import org.apache.zookeeper.CreateMode;
import java.nio.charset.StandardCharsets;
/**
* @author xl-9527
* @since 2024/12/14
**/
public class ServerRegistryImpl implements ServerRegistry {
private final String ip;
private final int port;
private final ZkCuratorFrameworkServerOps zkCuratorFrameworkServerOps;
public ServerRegistryImpl(final String ip, final int port) {
this.ip = ip;
this.port = port;
this.zkCuratorFrameworkServerOps = new ZkCuratorFrameworkServerOps();
}
@Override
public void registry(final String serviceName) {
// 基础的路径注册为永久节点
final String path = CustomRpcConfig.BASE_PATH + serviceName;
if (!zkCuratorFrameworkServerOps.exists(path)) {
zkCuratorFrameworkServerOps.createNode(path, null, true);
}
// 创建临时节点,这其实就是我们的服务的元数据信息
zkCuratorFrameworkServerOps.createNode(path + "/" + ip + ":" + port, (ip + ":" + port).getBytes(StandardCharsets.UTF_8), CreateMode.EPHEMERAL);
}
}