Spring Boot 2.2 集成 Spring Cloud Zookeeper - 分布式服务注册中心

1 摘要

Zookeeper 是一套分布式服务管理框架,在分布式系统中应用广泛,Zookeeper 常用的功能有:服务命名、配置管理、集群管理、同步管理等。

Zookeeper Linux 安装教程

(仅 Linux 系统支持安装和部署,建议直接安装 Linux 版)

本文将介绍 Spring Cloud Zookeeper 分布式服务注册中心的简易集成。

2 核心 Maven 依赖

./cloud-zookeeper-provider/pom.xml
        <!-- Spring mvc -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- Spring cloud zookeeper -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-zookeeper-all</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.apache.zookeeper</groupId>
                    <artifactId>zookeeper</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!-- Zookeeper -->
        <dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
            <version>${zookeeper.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-log4j12</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

其中 ${zookeeper.version} 的版本为 3.4.12 (不要随意改版本号,会有兼容性问题)

注意: SpringBoot 的版本需要在 2.2及以上

3 配置文件

3.1 bootstrap.yml
./cloud-zookeeper-provider/src/main/resources/bootstrap.yml
## Application bootstrap config


## spring config
spring:
  cloud:
    zookeeper:
      connect-string: 172.16.140.10:2181

Zookeeper 的连接信息 spring.cloud.zookeeper.connect-string 默认配置为 localhost:2181

Srping Cloud Zookeeper 的相关配置必须放在 bootstrap.yml / bootstrap.properties 中,而不能放在 application.yml / application.properties 中,否则会不生效

关于 bootstrap.ymlapplication.yml 两个配置文件的关系: bootstrap.yml 优先级高于 application.yml,且 bootstrap.yml 中的配置不会在 application.yml 中所覆盖,具体可参考:

SpringCloud入门之常用的配置文件 application.yml和 bootstrap.yml区别

3.2 application.yml
./cloud-zookeeper-provider/src/main/resources/application.yml
## Application config

## Server
server:
  port: 8100

## Spring config
spring:
  application:
    name: cloud-zookeeper-provider

Zookeeper 将应用的名称(spring.application.name) 作为注册服务的名称(serviceId)

4 相关 Java 类

4.1 SpringBoot 启动类
./cloud-zookeeper-provider/src/main/java/com/ljq/demo/springboot/cloud/zookeeper/provider/CloudZookeeperProviderApplication.java
package com.ljq.demo.springboot.cloud.zookeeper.provider;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @author junqiang.lu
 */
@SpringBootApplication
public class CloudZookeeperProviderApplication {

    public static void main(String[] args) {
        SpringApplication.run(CloudZookeeperProviderApplication.class, args);
    }

}

服务注册中心的 SpringBoot 启动类不需要其他额外的注解

4.2 Controller 类
./cloud-zookeeper-provider/src/main/java/com/ljq/demo/springboot/cloud/zookeeper/provider/controller/CloudZookeeperProviderController.java
package com.ljq.demo.springboot.cloud.zookeeper.provider.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * @Description: Zookeeper 注册中心控制层
 * @Author: junqiang.lu
 * @Date: 2020/2/23
 */
@RestController
@RequestMapping(value = "/api/cloud/zookeeper")
public class CloudZookeeperProviderController {

    /**
     * 服务端口
     */
    @Value("${server.port: 6666}")
    private String serverPort;

    @RequestMapping(value = "/hello", method = {RequestMethod.GET, RequestMethod.POST},
            produces = {MediaType.APPLICATION_JSON_VALUE})
    public ResponseEntity<String> hello(@RequestParam("name") String name) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("Hello !");
        stringBuilder.append(name).append("\n");
        stringBuilder.append("server port : ").append(serverPort).append("\n");
        stringBuilder.append("server timestamp: ").append(System.currentTimeMillis());

        System.out.println(new Date() + "-" + stringBuilder.toString());

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        return new ResponseEntity<>(stringBuilder.toString(), headers, HttpStatus.OK);
    }
}

作为示例,这个 hello 方法打印传入的 name 参数以及当前应用的端口号(serverPort,并非 Zookeeper 服务的端口号)

5 测试

5.1 启动日志

项目启动后会有一些和 Zookeeper 相关的必要日志,这里作者摘要部分

2020-02-23 19:37:38.160  INFO 31553 --- [  restartedMain] org.apache.zookeeper.ZooKeeper           : Initiating client connection, connectString=172.16.140.10:2181 sessionTimeout=60000 watcher=org.apache.curator.ConnectionState@3b183f10
2020-02-23 19:37:38.182  INFO 31553 --- [16.140.10:2181)] org.apache.zookeeper.ClientCnxn          : Opening socket connection to server 172.16.140.10/172.16.140.10:2181. Will not attempt to authenticate using SASL (unknown error)
2020-02-23 19:37:38.183  INFO 31553 --- [  restartedMain] o.a.c.f.imps.CuratorFrameworkImpl        : Default schema
2020-02-23 19:37:38.206  INFO 31553 --- [16.140.10:2181)] org.apache.zookeeper.ClientCnxn          : Socket connection established to 172.16.140.10/172.16.140.10:2181, initiating session
2020-02-23 19:37:38.219  INFO 31553 --- [16.140.10:2181)] org.apache.zookeeper.ClientCnxn          : Session establishment complete on server 172.16.140.10/172.16.140.10:2181, sessionid = 0x10000a5c8580008, negotiated timeout = 40000
2020-02-23 19:37:38.227  INFO 31553 --- [ain-EventThread] o.a.c.f.state.ConnectionStateManager     : State change: CONNECTED

这是 SpringBoot 应用程序连接 Zookeeper 服务的过程,在此过程中如果 Zookeeper 的服务没有启动,系统会持续打印尝试连接的日志,多次尝试之后若还是不能连接到服务,则应用启动失败

5.2 检查 Zookeeper 服务是否注册

登录 Zookeeper 服务,进行查看信息

## 查看是否注册服务,出现 cloud-zookeeper-provider,表明服务已经注册成功
[zk: localhost:2181(CONNECTED) 10] ls /services
[cloud-zookeeper-provider]

## 查看注册的服务中的节点信息
[zk: localhost:2181(CONNECTED) 11] ls /services/cloud-zookeeper-provider
[091aa6f9-1b21-4f7a-b954-1a897bf7e6ef]

## 只有一个子节点,子节点下边没有子节点
[zk: localhost:2181(CONNECTED) 12] ls /services/cloud-zookeeper-provider/091aa6f9-1b21-4f7a-b954-1a897bf7e6ef
[]

## 读取子节点信息
[zk: localhost:2181(CONNECTED) 13] get /services/cloud-zookeeper-provider/091aa6f9-1b21-4f7a-b954-1a897bf7e6ef
{"name":"cloud-zookeeper-provider","id":"091aa6f9-1b21-4f7a-b954-1a897bf7e6ef","address":"192.168.8.124","port":8100,"sslPort":null,"payload":{"@class":"org.springframework.cloud.zookeeper.discovery.ZookeeperInstance","id":"application-1","name":"cloud-zookeeper-provider","metadata":{}},"registrationTimeUTC":1582458903078,"serviceType":"DYNAMIC","uriSpec":{"parts":[{"value":"scheme","variable":true},{"value":"://","variable":false},{"value":"address","variable":true},{"value":":","variable":false},{"value":"port","variable":true}]}}
cZxid = 0x255
ctime = Sun Feb 23 17:28:49 CST 2020
mZxid = 0x255
mtime = Sun Feb 23 17:28:49 CST 2020
pZxid = 0x255
cversion = 0
dataVersion = 0
aclVersion = 0
ephemeralOwner = 0x10001265f030001
dataLength = 538
numChildren = 0

其中子节点的值用 json 格式显示如下:

{
    "name": "cloud-zookeeper-provider",
    "id": "091aa6f9-1b21-4f7a-b954-1a897bf7e6ef",
    "address": "192.168.8.124",
    "port": 8100,
    "sslPort": null,
    "payload": {
        "@class": "org.springframework.cloud.zookeeper.discovery.ZookeeperInstance",
        "id": "application-1",
        "name": "cloud-zookeeper-provider",
        "metadata": {}
    },
    "registrationTimeUTC": 1582458903078,
    "serviceType": "DYNAMIC",
    "uriSpec": {
        "parts": [
            {
                "value": "scheme",
                "variable": true
            },
            {
                "value": "://",
                "variable": false
            },
            {
                "value": "address",
                "variable": true
            },
            {
                "value": ":",
                "variable": false
            },
            {
                "value": "port",
                "variable": true
            }
        ]
    }
}

可以看到子节点中保存着注册服务的名称,子节点 id,注册服务应用的 ip、端口、注册时间等信息

Zookeeper 服务中看到节点信息,表明服务注册成功

5.3 http 请求测试
GET http://127.0.0.1:8100/api/cloud/zookeeper/hello?name=Are%20you%20%E6%AC%A7%E5%85%8B

请求结果:

Hello !Are you 欧克
server port : 8100
server timestamp: 1582459700041

至此,一个简易的 Spring Cloud Zookeeper 分布式服务注册中心搭建完成!

6 参考资料推荐

官方文档 Spring Cloud Zookeeper

Zookeeper 完整系列教程 Spring-Cloud-Zookeeper-Based-Demo

【feign】解决–feign.FeignException$MethodNotAllowed: status 405 reading

7 Github 源码

Gtihub 源码地址 : https://github.com/Flying9001/springBootDemo

个人公众号:404Code,分享半个互联网人的技术与思考,感兴趣的可以关注.
404Code

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值