服务注册

服务注册是将每个服务的网络地址和其他相关信息注册到一个中心化的服务注册中心(Service Registry)中的过程。

服务注册中心充当了服务目录的角色,用于存储和管理所有可用的服务信息。

服务注册的目的是为了实现分布式系统中的服务发现和通信。

对于服务注册,我们不仅提供了 Nacos 实现而且还提供了 Zookeeper 实现,默认使用 Nacos。

下面分别介绍下如果使用 Nacos 做注册中心在服务端需要做什么还有如果使用 Zookeeper 做注册中心需要做什么。

使用 Nacos 实现服务注册

  1. 引入 Nacos 依赖,版本可以使用最新的,这里仅作演示
<dependency>
    <groupId>com.alibaba.nacos</groupId>
    <artifactId>nacos-client</artifactId>
    <version>1.3.2</version>
</dependency>
  1. 注入 NamingService
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(ServerConfiguration.class)
@ConditionalOnBean(annotation = {EnableOpenRpcServer.class})
public class ServerAutoConfiguration {

    @Bean
    public NamingService namingService() throws NacosException {
        Properties properties = new Properties();
        properties.put(PropertyKeyConst.USERNAME, "nacos");
        properties.put(PropertyKeyConst.PASSWORD, "nacos");
        properties.put(PropertyKeyConst.SERVER_ADDR, "127.0.0.1:8848");
        return NacosFactory.createNamingService(properties);
    }

    // ~

}

使用 Zookeeper 实现服务注册

  1. 引入 Zookeeper 依赖,版本可以使用最新的,这里仅作演示
<dependency>
    <groupId>org.apache.zookeeper</groupId>
    <artifactId>zookeeper</artifactId>
    <version>3.7.0</version>
</dependency>

<dependency>
    <groupId>com.101tec</groupId>
    <artifactId>zkclient</artifactId>
    <version>0.11</version>
</dependency>
  1. 注入 ZkClient 以及 RegistryService,因为系统默认使用 Nacos 做服务注册
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(ServerConfiguration.class)
@ConditionalOnBean(annotation = {EnableOpenRpcServer.class})
public class ServerAutoConfiguration {

    @Bean(destroyMethod = "close")
    public ZkClient zkClient(){
        System.setProperty("zookeeper.sasl.client", "false");
        return new ZkClient("192.168.1.26:2181,192.168.1.27:2181,192.168.1.28:2181", 5000);
    }

    @Bean
    public RegistryService registryService(ZkClient zkClient,
                                           ServerConfiguration configuration){
        return new ZookeeperRegistryService(zkClient, configuration);
    }

    // ~
}

拓展服务注册方式

例如你可以使用 Redis 实现服务注册