Spring Boot 2.2 集成 Spring Cloud Zookeeper - Ribbon 分布式服务消费者

1 摘要

Spring Cloud Zookeeper 分布式服务注册中心搭建可参考:

33 Spring Boot 2.2 集成 Spring Cloud Zookeeper - 分布式服务注册中心 — 2020-02-23

本文将介绍 Spring Cloud Zookeeper 分布式服务消费者 - Ribbon

2 核心 Maven 依赖

./cloud-zookeeper-ribbon/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-ribbon/src/main/resources/bootstrap.yml
## Application bootstrap config


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

3.2 application.yml

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

## Server
server:
  port: 8101

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

4 核心 Java 类

4.1 Service 层服务调用

./cloud-zookeeper-ribbon/src/main/java/com/ljq/demo/springboot/cloud/zookeeper/ribbon/service/CloudZookeeperRibbonService.java
package com.ljq.demo.springboot.cloud.zookeeper.ribbon.service;

import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @Description: Spring Cloud Zookeeper Ribbon 服务消费者业务层
 * @Author: junqiang.lu
 * @Date: 2020/2/24
 */
@Service("cloudZookeeperRibbonService")
public class CloudZookeeperRibbonService {

    /**
     * Zookeeper 服务注册中心服务名称
     */
    private static final String CLOUD_ZOOKEEPER_PROVIDER_NAME = "cloud-zookeeper-provider";
    /**
     * Zookeeper 服务注册中心接口地址-打印用户名称
     */
    private static final String API_PATH_ZOOKEEPER_HELLO = "/api/cloud/zookeeper/hello";


    @Resource
    private RestTemplate restTemplate;

    /**
     * 打印用户名称
     *
     * @param name
     * @return
     */
    public String sayHello(String name) {
        StringBuilder reqUrl = new StringBuilder("http://");
        reqUrl.append(CLOUD_ZOOKEEPER_PROVIDER_NAME);
        reqUrl.append(API_PATH_ZOOKEEPER_HELLO);
        reqUrl.append("?name=").append(name);

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

        return restTemplate.getForEntity(reqUrl.toString(), String.class).getBody();
    }


}

使用 RestTemplate 来请求调用 Zookeeper 服务,这里 Ribbon 将服务名称(ServiceId) 来替代 ip + 端口(port),RestTemplate 默认是正常的 http 请求,这里需要对 RestTemplate 使用 Ribbon 提供的注解 @LoadBalanced ,具体使用见 SpringBoot 启动类 com.ljq.demo.springboot.cloud.zookeeper.ribbon.CloudZookeeperRibbonApplication

关于 Ribbon@LoadBalanced 注解,其作用是实现客户端负载均衡,具体说明可参考:

由springcloud ribbon的 @LoadBalanced注解的使用理解

4.2 Controller 层

./cloud-zookeeper-ribbon/src/main/java/com/ljq/demo/springboot/cloud/zookeeper/ribbon/controller/CloudZookeeperRibbonController.java
package com.ljq.demo.springboot.cloud.zookeeper.ribbon.controller;

import com.ljq.demo.springboot.cloud.zookeeper.ribbon.service.CloudZookeeperRibbonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
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;

/**
 * @Description: Spring cloud Zookeeper Ribbon 服务消费者控制层
 * @Author: junqiang.lu
 * @Date: 2020/2/24
 */
@RestController
@RequestMapping("/api/cloud/zookeeper/ribbon")
public class CloudZookeeperRibbonController {

    @Autowired
    private CloudZookeeperRibbonService cloudZookeeperRibbonService;


    /**
     * 打印用户名称
     *
     * @param name
     * @return
     */
    @RequestMapping(value = "/sayHello", method = {RequestMethod.GET, RequestMethod.POST},
            produces = {MediaType.APPLICATION_JSON_VALUE})
    public String sayHello(@RequestParam("name") String name) {
        return cloudZookeeperRibbonService.sayHello(name);
    }


}

4.3 SpringBoot 启动类

./cloud-zookeeper-ribbon/src/main/java/com/ljq/demo/springboot/cloud/zookeeper/ribbon/CloudZookeeperRibbonApplication.java
package com.ljq.demo.springboot.cloud.zookeeper.ribbon;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

/**
 * @author junqiang.lu
 */
@EnableDiscoveryClient
@SpringBootApplication
public class CloudZookeeperRibbonApplication {

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

    @LoadBalanced
    @Bean
    RestTemplate restTemplate(){
        return new RestTemplate();
    }


}

@EnableDiscoveryClient 该注解可用于发现 Cloud 服务

@LoadBalanced 用于负载均衡,这里必须手动注入 RestTemplate,并使用 @LoadBalanced 注解,否则, RestTemplate 默认使用正常的 http 请求

5 测试

由于本次测试需要调用 Spring Cloud Zookeeper 服务,因此服务注册中心的项目(cloud-zookeeper-provider)必须先启动

接口请求:

GET http://127.0.0.1:8101/api/cloud/zookeeper/ribbon/sayHello?name=Are%20you%20%E6%AC%A7%E5%85%8B

返回结果:

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

从返回的结果中可以看出,返回的端口为服务注册中心项目( cloud-zoopeeper-provider)的http端口,使用 Ribbon 调用 Cloud Zoopeeper 服务成功

6 推荐参考资料

官方文档 Spring Cloud Zookeeper

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

由springcloud ribbon的 @LoadBalanced注解的使用理解

7 Github 源码

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

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

发布了61 篇原创文章 · 获赞 65 · 访问量 20万+

猜你喜欢

转载自blog.csdn.net/Mrqiang9001/article/details/104495167