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