自定义服务的服务注册- zookeeper

自定义服务的服务注册- zookeeper

服务注册使用 zookeeper 的大致过程如下

  1. 链接 zookeeper 集群或者单机
  2. 注册自己的 ip + 端口到 zookeeper 的 node(这个 node 要是临时节点的,因为可以保证健康检查以及服务发现的高可用

编码实现

java 复制代码
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);
    }
}
相关推荐
阿里云云原生3 天前
阿里云获评 Agentic AI 开发平台领导者,函数计算 AgentRun 赢下关键分!
云原生
初次攀爬者3 天前
ZooKeeper 实现分布式锁的两种方式
分布式·后端·zookeeper
阿里云云原生4 天前
MSE Nacos Prompt 管理:让 AI Agent 的核心配置真正可治理
微服务·云原生
阿里云云原生4 天前
当 AI Agent 接管手机:移动端如何进行观测
云原生·agent
阿里云云原生4 天前
AI 原生应用开源开发者沙龙·深圳站精彩回顾 & PPT下载
云原生
阿里云云原生4 天前
灵感启发:日产文章 100 篇,打造“实时热点洞察”引擎
云原生
~莫子4 天前
Haproxy七层负载详解+实验详细代码
云原生
阿里云云原生4 天前
OpenTelemetry + 云监控 2.0:打造你的云原生全栈可观测
云原生
阿狸猿4 天前
云原生数据库
云原生·软考
至此流年莫相忘4 天前
Kubernetes实战篇之配置与存储
云原生·容器·kubernetes