Spring Cloud Finchley.SR1 的学习与应用 6 - 服务消费

本文详细介绍微服务架构下,服务消费者如何通过不同方式调用服务提供者,包括使用LoadBalancerClient、Ribbon和Feign,展示了具体的代码实现及配置。

Ribbon

服务提供者

服务提供者已经在《Spring Cloud Finchley.SR1 的学习与应用 4 - 服务注册》一文中做了明确说明,这里不在赘述了。

服务消费者

创建服务消费者根据使用 API 的不同,大致分为三种方式。虽然大家在实际使用中用的应该都是 Feign,但是这里还是把这三种都介绍一下

创建业务系统B,与业务系统A类似

  • 创建modules-woqu,继承parent-woqu,用于管理业务系统项目
<?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>modules-woqu</artifactId>
        <groupId>com.orrin</groupId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>businessb-woqu</artifactId>
    <packaging>pom</packaging>
    <modules>
        <module>client-businessb-woqu</module>
        <module>server-businessb-woqu</module>
    </modules>


    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

    </dependencies>
</project>
  • 创建businessa-woqu业务系统B

包含业务系统客户端client-businessb-woqu和服务端server-businessb-woqu

<?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>businessb-woqu</artifactId>
        <groupId>com.orrin</groupId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>client-businessb-woqu</artifactId>


    <dependencies>
        <dependency>
            <groupId>com.orrin</groupId>
            <artifactId>model-woqu</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>


        <dependency>
            <groupId>com.orrin</groupId>
            <artifactId>core-woqu</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
    </dependencies>
</project>
  • 业务系统B服务端

下面我们服务消费的客户端,并向服务注册中心注册自己。 假设我们有一个提供长方体表面积计算功能的微服务模块,我们实现一个RESTful API,通过传入三个参数length、width、heigh,最后返回长方体表面积。

创建client-businessa-woqu

<?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>businessb-woqu</artifactId>
        <groupId>com.orrin</groupId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>server-businessb-woqu</artifactId>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-consul-discovery</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

        <dependency>
            <groupId>org.jolokia</groupId>
            <artifactId>jolokia-core</artifactId>
        </dependency>

        <dependency>
            <groupId>com.orrin</groupId>
            <artifactId>client-businessa-woqu</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>com.orrin</groupId>
            <artifactId>client-businessb-woqu</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>

    </dependencies>

</project>

配置文件

spring:
  application:
    name: business-b-woqu
  cloud:
    consul:
      host: woqu.consul
      port: 8500
      discovery:
        instance-id: ${spring.application.name}
        instance-group: ${spring.application.name}
        register: true

server:
  port: 9002
  
feign:
  hystrix:
    enabled: true

logging:
  level:
    root: info
    com.woqu: debug
    
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds: 60000
ribbon:
  ConnectTimeout: 10000
  ReadTimeout: 60000

启动类:

package com.woqu.business.b.server;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.ComponentScan;

/**
 * @author orrin
 */

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients(basePackages = "com.woqu")
@ComponentScan(value = "com.woqu")
public class BusinessBApp {
    public static void main(String[] args) {
        SpringApplication.run(BusinessBApp.class, args);
    }
}

使用 LoadBalancerClient

初始化RestTemplate,用来发起 REST 请求。

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

创建一个接口用来消费 producer(business-a-woqu) 提供的接口:

@RestController
public class ConsumeController {

    @Autowired
    private LoadBalancerClient client;

    @Autowired
    private RestTemplate restTemplate;
    
    private Integer multiply(int x, int y) {
        return x * y;
    }
    
    @GetMapping("/area/2")
    public Integer cuboidArea2(@RequestParam("length") int length, @RequestParam("width") int width, @RequestParam("heigh") int heigh) {
        LOGGER.info("length = {}, width = {}, heigh = {}");
        return  this.multiply(2, this.add2(this.add2(this.multiply(length, width), this.multiply(width, heigh)), this.multiply(length, heigh)));
    }

    /**
     * 使用 LoadBalancerClient 消费business-a-woqu中的方法
     */
    private Integer add2(int x, int y) {
        ServiceInstance instance = client.choose("business-a-woqu");
        String url = "http://" + instance.getHost() + ":" + instance.getPort() + "/add?x=" + x + "&y=" + y;
        return restTemplate.getForObject(url, Integer.class);
    }
}

可以看到这里,我们注入了LoadBalancerClient和RestTemplate,并在hello方法中,先通过loadBalancerClient的choose方法来负载均衡的选出一个business-a-woqu的服务实例,这个服务实例的基本信息存储在ServiceInstance中,然后通过这些对象中的信息拼接出访问服务调用者的/add接口的详细地址,最后再利用RestTemplate对象实现对服务提供者接口的调用。

验证是否调用成功

GET http://127.0.0.1:9002/area/2?length=1&width=2&heigh=3

HTTP/1.1 200 
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Mon, 19 Nov 2018 06:29:45 GMT

22

Response code: 200; Time: 1576ms; Content length: 2 bytes
Spring Cloud Ribbon

Ribbon是一个基于 HTTP 和 TCP 的客户端负载均衡器。它可以通过在客户端中配置 ribbonServerList 来设置服务端列表去轮询访问以达到均衡负载的作用。

为RestTemplate添加@LoadBalanced注解

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

修改 controller,去掉LoadBalancerClient,并修改相应的方法,直接用 RestTemplate发起请求

@RestController
public class ConsumeController {
    private Integer multiply(int x, int y) {
        return x * y;
    }
    
    /**
     * 使用 Ribbon 消费business-a-woqu中的方法
     */
    private Integer add3(int x, int y) {
        ServiceInstance instance = client.choose("business-a-woqu");
        String url = "http://business-a-woqu/add?x=" + x + "&y=" + y;
        return restTemplate.getForObject(url, Integer.class);
    }

    @GetMapping("/area/3")
    public Integer cuboidArea3(@RequestParam("length") int length, @RequestParam("width") int width, @RequestParam("heigh") int heigh) {
        LOGGER.info("length = {}, width = {}, heigh = {}");
        return  this.multiply(2, this.add3(this.add3(this.multiply(length, width), this.multiply(width, heigh)), this.multiply(length, heigh)));
    }
}

这里直接用服务名eureka-producer取代了之前的具体的host:port。那么这样的请求为什么可以调用成功呢?因为 Spring Cloud Ribbon 有一个拦截器,它能够在这里进行实际调用的时候,自动的去选取服务实例,并将这里的服务名替换成实际要请求的 IP 地址和端口,从而完成服务接口的调用。

验证是否调用成功

GET http://192.168.2.102:9002/area/3?length=2&width=2&heigh=3

HTTP/1.1 200 
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Mon, 19 Nov 2018 06:47:17 GMT

32

Response code: 200; Time: 67ms; Content length: 2 bytes
使用 Spring Cloud Feign

在实际工作中,我们基本上都是使用 Feign 来完成调用的。我们通过一个例子来展现 Feign 如何方便的声明对 business-a-woqu 服务的定义和调用。

  • POM 包配置
    在 pom.xml 中添加如下配置:
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
  • 启动类
    @EnableFeignClients(basePackages = "com.woqu")
/**
 * @author orrin
 */

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients(basePackages = "com.woqu")
@ComponentScan(value = "com.woqu")
public class BusinessBApp {
    public static void main(String[] args) {
        SpringApplication.run(BusinessBApp.class, args);
    }
}
  • Feign 调用实现
    创建一个 Feign 的客户端接口定义。使用@FeignClient注解来指定这个接口所要调用的服务名称,接口中定义的各个函数使用 Spring MVC 的注解就可以来绑定服务提供方的 REST 接口,比如下面就是绑定 business-a-woqu 服务的/add接口的例子:
/**
 * @author orrin on 2018/7/4
 */
@FeignClient(serviceId = "business-a-woqu")
public interface Addition {

    @GetMapping("/add")
    public Integer add(@RequestParam("x") int x, @RequestParam("y") int y);
}

此类中的方法和远程服务中 Contoller 中的方法名和参数需保持一致。

  • Controller
    修改 Controller,将 HelloRemote 注入到 controller 层,像普通方法一样去调用即可
@RestController
public class ConsumeController {
    @Autowired
    private Addition a;
    
    
    private Integer multiply(int x, int y) {
        return x * y;
    }
    
    @GetMapping("/area")
    public Integer cuboidArea(@RequestParam("length") int length, @RequestParam("width") int width, @RequestParam("heigh") int heigh) {
        LOGGER.info("length = {}, width = {}, heigh = {}");
        return  this.multiply(2, a.add(a.add(this.multiply(length, width), this.multiply(width, heigh)), this.multiply(length, heigh)));
    }
}

通过 Spring Cloud Feign 来实现服务调用的方式非常简单,通过@FeignClient定义的接口来统一的声明我们需要依赖的微服务接口。而在具体使用的时候就跟调用本地方法一点的进行调用即可。由于 Feign 是基于 Ribbon 实现的,所以它自带了客户端负载均衡功能,也可以通过 Ribbon 的 IRule 进行策略扩展。另外,Feign 还整合的 Hystrix 来实现服务的容错保护,这个在后边会详细讲。

验证是否调用成功

GET http://192.168.2.102:9002/area?length=1&width=2&heigh=3

HTTP/1.1 200 
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Mon, 19 Nov 2018 06:57:52 GMT

22

Response code: 200; Time: 525ms; Content length: 2 bytes

转载于:https://my.oschina.net/orrin/blog/2885676

项目说明 该项目是一个典型的由Spring Cloud管理的微服务项目,主要包括如下模块 micro-service-cloud─────────────────顶层项目 ├──cloud-service-core───────────────基础核心模块 ├──cloud-service-tools──────────────全局通用工具类 ├──cloud-service-reids──────────────Redis二次封装 ├──cloud-eureka-server──────────────服务注册中心[8761] ├──cloud-turbine-server─────────────断路器聚合监控[8769] ├──cloud-zipkin-server──────────────链路追踪监控[9411] ├──cloud-zuul-server────────────────第一代服务网关(Zuul)[8080] ├──cloud-gateway-server─────────────第二代服务网关(Gateway)[8080] ├──cloud-modules-app────────────────App微服务模块 ├───────modules-app-user────────────App用户服务模块[努力更新中] ├───────modules-app-doctor──────────App医生服务模块[努力更新中] ├──cloud-modules-service────────────微服务通用服务模块 ├───────mongodb-file-service────────Mongodb文件服务模块[11010] ├───────redis-delay-service─────────延迟消费服务模块[11020] ├──cloud-modules-web────────────────Web微服务模块 ├───────modules-web-security────────Web医生服务模块[12010] ├───────modules-web-user────────────Web用户服务模块[12020] ├──cloud-modules-wechat─────────────Wechat微服务模块 ├───────modules-wechat-user─────────Wechat用户服务模块[努力更新中] └───────modules-wechat-doctor───────Wechat医生服务模块[努力更新中] 修改日志 修改日志 修改人 修改日期 版本计划 V1.0 刘岗强 2019-01-07 项目初始化 V1.1 刘岗强 待定 新增自动问答 项目介绍 基于Spring Cloud Finchley SR2 Spring Boot 2.0.7的最新版本。 核心基础项目内实现类自定义的权限注解,配合RBAC权限模型+拦截器即可实现权限的控制,具体的参考项目中的实现。同时也封装了一些顶层类和结果集等。 注册中心实现高可用配置,详情见eureka的one、two、three三个配置文件,摘要如下。 ------------------------------------------配置节点一---------------------------------------------- server: port: 8761 spring: application: name: cloud-eureka-server eureka: instance: hostname: cloud.server.one prefer-ip-address: true instance-id: ${spring.cloud.client.ip-address}:${server.port}:${spring.application.name} client: healthcheck: enabled: true register-with-eureka: false fetch-registry: false service-url: defaultZone: http://cloud.server.two:8762/eureka/,http://cloud.server.three:8763/eureka/ ------------------------------------------配置节点二----------------------------------------------
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值