为了账号安全,请及时绑定邮箱和手机立即绑定

SpringCloud-03-Zookeeper

标签:
Spring Cloud

在前面介绍SpringCloud Eureka已经停止更新,如果担心Eureka技术过时,可以选用 Zookeeper 作为注册中心,作为服务注册与发现。其实了解Dubbo的朋友应该知道。在Dubbo中,也是推荐使用Zookeeper作为注册中心,Dubbo是一门RPC框架,用于远程过程调用,在这里就不对Dubbo进行介绍。
ZooKeeper 是一个开放源代码的分布式协调服务,在之前,我已经写过几篇关于Zookeeper的文章,在系列文章中讲解了Zookeeper的作用,原理,安装和简单使用。不了解Zookeeper的工作原理的朋友,需要先去翻翻前面我写的Zookeeper相关的文章。

接下来就演示如何使用 Zookeeper 作为注册中心,实现服务注册与发现。
业务场景:用户服务UserService通过Zookeeper注册中心,获取微信服务WechatService的服务列表,然后发送http请求,获取用户的微信用户信息。
整个过程如图所示:

1 搭建Zookeeper集群

1.1 配置和启动 192.168.43.51上的Zookeeper服务

上传 zookeeper安装包并解压,复制 zoo_sample.cfg 为配置文件 zoo.cfg。

[tag@localhost ~]$ ll apache-zookeeper-3.6.1-bin.tar.gz 
-rw-r--r--. 1 tag tag 12436328 8月  10 2020 apache-zookeeper-3.6.1-bin.tar.gz
[tag@localhost ~]$ tar -zxvf apache-zookeeper-3.6.1-bin.tar.gz 
[tag@localhost ~]$ mv apache-zookeeper-3.6.1-bin zk-3.6.1
[tag@localhost ~]$ cd zk-3.6.1/conf
[tag@localhost conf]$ cp zoo_sample.cfg zoo.cfg
[tag@localhost conf]$ 

修改配置文件 zoo.cfg

[tag@localhost conf]$ vim zoo.cfg 
# The number of milliseconds of each tick
tickTime=2000
# The number of ticks that the initial 
# synchronization phase can take
initLimit=10
# The number of ticks that can pass between 
# sending a request and getting an acknowledgement
syncLimit=5
# the directory where the snapshot is stored.
# do not use /tmp for storage, /tmp here is just 
# example sakes.
#配置 ZooKeeper 服务器存储快照文件的目录
dataDir=/home/tag/zk-3.6.1/data
# the port at which the clients will connect
clientPort=2181
# the maximum number of client connections.
# increase this if you need to handle more clients
#maxClientCnxns=60
#
# Be sure to read the maintenance section of the 
# administrator guide before turning on autopurge.
#
# http://zookeeper.apache.org/doc/current/zookeeperAdmin.html#sc_maintenance
#
# The number of snapshots to retain in dataDir
#autopurge.snapRetainCount=3
# Purge task interval in hours
# Set to "0" to disable auto purge feature
#autopurge.purgeInterval=1

server.1=192.168.43.51:2888:3888
server.2=192.168.43.52:2888:3888
server.3=192.168.43.53:2888:3888

新增 myid 文件

[tag@localhost conf]$ mkdir /home/tag/zk-3.6.1/data
[tag@localhost conf]$ cd /home/tag/zk-3.6.1/data
[tag@localhost data]$ vi myid
1
~    

启动zookeeper服务,可以看到 2181 端口已启动成功

[tag@localhost data]$ /home/tag/zk-3.6.1/bin/zkServer.sh start
ZooKeeper JMX enabled by default
Using config: /home/tag/zk-3.6.1/bin/../conf/zoo.cfg
Starting zookeeper ... STARTED
[tag@localhost data]$ ss -nultp | grep 2181
tcp    LISTEN     0      50       :::2181                 :::*                   users:(("java",pid=31393,fd=56))

1.2 配置和启动 192.168.43.52 和 192.168.43.53上 的Zookeeper服务

根据192.168.43.51机器上的zookeeper服务安装步骤,搭建zookeeper。
**注意:**在192.168.43.52上修改数据目录/home/tag/zk-3.6.1/data下面的myid文件内容为2,而192.168.43.53中的myid文件内容为3。

修改好了myid文件后,分别启动zookeeper服务。

查看集群状态

192.168.43.51

[tag@localhost ~]$ /home/tag/zk-3.6.1/bin/zkServer.sh status
ZooKeeper JMX enabled by default
Using config: /home/tag/zk-3.6.1/bin/../conf/zoo.cfg
Client port found: 2181. Client address: localhost.
Mode: follower

192.168.43.52

[tag@localhost ~]$ /home/tag/zk-3.6.1/bin/zkServer.sh status
ZooKeeper JMX enabled by default
Using config: /home/tag/zk-3.6.1/bin/../conf/zoo.cfg
Client port found: 2181. Client address: localhost.
Mode: leader

192.168.43.53

[tag@localhost ~]$ /home/tag/zk-3.6.1/bin/zkServer.sh status
ZooKeeper JMX enabled by default
Using config: /home/tag/zk-3.6.1/bin/../conf/zoo.cfg
Client port found: 2181. Client address: localhost.
Mode: follower

可以看到 192.168.43.52 为leader节点,而192.168.43.51和192.168.43.53分别为follower节点

2. 搭建服务提供者 provider-zk-wechat9101

搭建 wechatService 的第一个服务实例 9101。

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>006SpringCloud</artifactId>
        <groupId>com.xander</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>provider-zk-wechat9101</artifactId>


    <dependencies>
        <!-- spring-cloud-starter-zookeeper-discovery -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-zookeeper-discovery</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--common-api-->
        <dependency>
            <groupId>com.xander</groupId>
            <artifactId>common-api</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

    </dependencies>

</project>

application.yml

server:
  port: 9101


spring:
  application:
    # 微服务名称
    name: wechatService
  cloud:
    zookeeper:
      #Zookeeper服务连接地址,如果是集群,使用逗号分隔
      connect-string: 192.168.43.51:2181,192.168.43.51:2181,192.168.43.51:2181
      discovery:
        # 服务实例注册进zookeeper的host
        instance-host: 127.0.0.1

服务启动类 ProviderZkWechat9101.java,添加 @EnableDiscoveryClient 注解

@SpringBootApplication
@EnableDiscoveryClient
public class ProviderZkWechat9101 {
    public static void main(String[] args) {
        SpringApplication.run(ProviderZkWechat9101.class, args);
    }
}

新建实体类 WechatInfo


/**
 * Description: 模拟微信用户信息
 *
 * @author Xander
 * datetime: 2021-05-14 16:24
 */
public class WechatInfo {

    private String userName;
    
    private String openId;
    
    public static WechatInfo newInstance() {
        WechatInfo instance = new WechatInfo();
        return instance;
    }

    public String getUserName() {
        return userName;
    }

    public WechatInfo setUserName(String userName) {
        this.userName = userName;
        return this;
    }

    public String getOpenId() {
        return openId;
    }

    public WechatInfo setOpenId(String openId) {
        this.openId = openId;
        return this;
    }
}

WechatController

@RestController
@RequestMapping("/wechat")
public class WechatController {

    @Value("${server.port}")
    private String serverPort;

    @GetMapping(value = "/getByUserId/{userId}")
    public CommonResult<WechatInfo> getWechatInfo(@PathVariable("userId") Long userId) {
        WechatInfo wechatInfo = WechatInfo.newInstance().setOpenId(userId + "-openId").setUserName(userId + "-name");
        return CommonResult.newInstance().setCode(200).setMessage("查询成功,serverPort:" + serverPort).setData(wechatInfo);
    }
}

3. 搭建服务提供者 provider-zk-wechat9102

搭建 wechatService 的第二个服务实例 9102。

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>006SpringCloud</artifactId>
        <groupId>com.xander</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>provider-zk-wechat9102</artifactId>


    <dependencies>
        <!-- spring-cloud-starter-zookeeper-discovery -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-zookeeper-discovery</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--common-api-->
        <dependency>
            <groupId>com.xander</groupId>
            <artifactId>common-api</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

    </dependencies>

</project>

application.yml

server:
  port: 9102


spring:
  application:
    # 微服务名称
    name: wechatService
  cloud:
    zookeeper:
      #Zookeeper服务连接地址,如果是集群,使用逗号分隔
      connect-string: 192.168.43.51:2181,192.168.43.51:2181,192.168.43.51:2181
      discovery:
        # 服务实例注册进zookeeper的host
        instance-host: 127.0.0.1

服务启动类 ProviderZkWechat9102.java,添加 @EnableDiscoveryClient 注解

@SpringBootApplication
@EnableDiscoveryClient
public class ProviderZkWechat9102 {
    public static void main(String[] args) {
        SpringApplication.run(ProviderZkWechat9102.class, args);
    }
}

WechatController

@RestController
@RequestMapping("/wechat")
public class WechatController {

    @Value("${server.port}")
    private String serverPort;

    @GetMapping(value = "/getByUserId/{userId}")
    public CommonResult<WechatInfo> getByUserId(@PathVariable("userId") Long userId) {
        WechatInfo wechatInfo = WechatInfo.newInstance().setOpenId(userId + "-openId").setUserName(userId + "-name");
        return CommonResult.newInstance().setCode(200).setMessage("查询成功,serverPort:" + serverPort).setData(wechatInfo);
    }
}

4. 搭建服务提供者 consumer-zk-user8101

4.1 Eureka-client 和 zookeeper-discovery 都已内置Ribbon

在SpringCloud 的服务发现组件中,都已经内置了 Ribbon 组件,可直接配置客户端的负载均衡策略。

Eureka-client内置了Ribbon

zookeeper-discovery内置了Ribbon

4.2 新建module consumer-zk-user8101

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>006SpringCloud</artifactId>
        <groupId>com.xander</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>consumer-zk-user8101</artifactId>


    <dependencies>
        <!-- spring-cloud-starter-zookeeper-discovery -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-zookeeper-discovery</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--common-api-->
        <dependency>
            <groupId>com.xander</groupId>
            <artifactId>common-api</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

    </dependencies>

</project>

application.yml

server:
  port: 8101


spring:
  application:
    # 微服务名称
    name: userService
  cloud:
    zookeeper:
      #Zookeeper服务连接地址,如果是集群,使用逗号分隔
      connect-string: 192.168.43.51:2181,192.168.43.51:2181,192.168.43.51:2181
      discovery:
        # 服务实例注册进zookeeper的host
        instance-host: 127.0.0.1

服务启动类 ConsumerZkUser8101.java,添加 @EnableDiscoveryClient 注解

@SpringBootApplication
@EnableDiscoveryClient
public class ConsumerZkUser8101 {
    public static void main(String[] args) {
        SpringApplication.run(ConsumerZkUser8101.class, args);
    }
}

应用配置类AppConfig,配置Ribbon策略

/**
 * Description: 应用配置类
 *
 * @author Xander
 * datetime: 2021-05-11 18:18
 */
@Configuration
public class AppConfig {

    /**
     * 配置应用的负载均衡规则为轮询策略 RoundRobinRule
     *
     * @return
     */
    @Bean
    public IRule rule() {
        return new RoundRobinRule();
    }

    @Bean
    @LoadBalanced //开启 Ribbon 功能
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}

UserController

@RestController
@RequestMapping("/user")
public class UserController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    public static final String WECHAT_SERVICE = "wechatService";

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping(value = "/wechatInfo/{userId}")
    public CommonResult<WechatInfo> wechatInfo(@PathVariable("userId") Long userId) {
        List<ServiceInstance> instances = this.discoveryClient.getInstances(WECHAT_SERVICE);
        // 打印服务实例信息
        for (ServiceInstance instance : instances) {
            this.logger.info("serviceId: " + instance.getServiceId() + "\t" + "host: " + instance.getHost() + "\t"
                    + "port: " + instance.getPort() + "\t" + "uri: " + instance.getUri());
        }
        return this.restTemplate.getForObject("http://" + WECHAT_SERVICE + "/wechat/getByUserId/" + userId, CommonResult.class);
    }
}

5. 分别启动2个wechatServcie和userServcie

启动后,在zookeeper中的任意一台机器上查看服务注册信息,可以看到userService, wechatService都已经成功注册进zookeeper注册中心,其中userService包含一个服务实例,而wechatService有两个服务实例。

[tag@localhost ~]$ zk-3.6.1/bin/zkCli.sh 
[zk: localhost:2181(CONNECTED) 1] ls /
[services, zookeeper]
[zk: localhost:2181(CONNECTED) 2] ls /services
[userService, wechatService]
[zk: localhost:2181(CONNECTED) 3] ls /services/wechatService
[77ff5bfc-4779-47ed-9b81-621b558326e5, ca38ab47-8e0f-4723-b9dc-77bf50a59aca]
[zk: localhost:2181(CONNECTED) 4] ls /services/userService
[38f6bcfa-1a77-4948-b077-b3155ee81142]
[zk: localhost:2181(CONNECTED) 5] 

6. 服务调用

在浏览器上调用两次 http://localhost:8101/user/wechatInfo/1 ,响应成功并且我们配置的ribbon轮询策略起作用了,端口本别调用 9101、9102。

再来看看我们在 consumer-zk-user8101 中打印的服务信息,可以看到在 userService 中可以通过zookeeper注册中心拉取到 wechatService 的两个服务信息。

2021-05-14 17:54:43.326  INFO 3204 --- [nio-8101-exec-1] c.xander.user.controller.UserController  : serviceId: wechatService	host: 127.0.0.1	port: 9101	uri: http://127.0.0.1:9101
2021-05-14 17:54:43.326  INFO 3204 --- [nio-8101-exec-1] c.xander.user.controller.UserController  : serviceId: wechatService	host: 127.0.0.1	port: 9102	uri: http://127.0.0.1:9102
点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消