Spring Cloud Ribbon客户端负载均衡
目录
- Ribbon简介
- RestTemplate详解
- Spring Cloud Ribbon配置
为了提高服务的可用性,我们一般会将相同的服务部署多个实例,负载均衡的作用就是使获取服务的请求被均衡的分配到各个实例中。负载均衡一般分为服务端负载均衡和客户端负载均衡,服务端的负载均衡通过硬件(如F5)或者软件(如Nginx)来实现,而Ribbon实现的是客户端负载均衡。服务端负载均衡是在硬件设备或者软件模块中维护一份可用服务清单,然后客户端发送服务请求到这些负载均衡的设备上,这些设备根据一些算法均衡的将请求转发出去。而客户端负载均衡则是客户端自己从服务注册中心(如之前提到的Eureka Server)中获取服务清单缓存到本地,然后通过Ribbon内部算法均衡的去访问这些服务。
Ribbon简介
Ribbon是由Netflix开发的一款基于HTTP和TCP的负载均衡的开源软件。我们可以直接给Ribbon配置好服务列表清单,也可以配合Eureka主动的去获取服务清单,需要使用到这些服务的时候Ribbon通过轮询或者随机等均衡算法去获取服务。
在Spring Cloud Eureka服务治理一节中,我们已经在Server-Consumer中配置了Ribbon,并通过加了@LoadBalanced注解的RestTemplate对象去均衡的消费服务,所以这节主要记录的是RestTemplate的详细使用方法和一些额外的Ribbon配置。
RestTemplate详解
从名称上来看就可以知道它是一个用来发送REST请求的摸板,所以包含了GET,POST,PUT,DELETE等HTTP Method对应的方法。
在之前的项目Spring Cloud Eureka服务治理上继续添加代码
只需要用到Eureka-Server和Eureka-Client
Eureka-Server不变Eureka-Client基础上加以下代码:
UserController类:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39 1@RestController
2@RequestMapping("user")
3public class UserController {
4
5 private Logger log = LoggerFactory.getLogger(this.getClass());
6
7 @GetMapping("/{id:\\d+}")
8 public User get(@PathVariable Long id) {
9 log.info("获取用户id为 " + id + "的信息");
10 return new User(id, "mrbird", "123456");
11 }
12
13 @GetMapping
14 public List<User> get() {
15 List<User> list = new ArrayList<>();
16 list.add(new User(1L, "mrbird", "123456"));
17 list.add(new User(2L, "scott", "123456"));
18 log.info("获取用户信息 " + list);
19 return list;
20 }
21
22 @PostMapping
23 public void add(@RequestBody User user) {
24 log.info("新增用户成功 " + user);
25 }
26
27 @PutMapping
28 public void update(@RequestBody User user) {
29 log.info("更新用户成功 " + user);
30 }
31
32 @DeleteMapping("/{id:\\d+}")
33 public void delete(@PathVariable Long id) {
34 log.info("删除用户成功 " + id);
35 }
36
37}
38
39
User类:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53 1public class User implements Serializable {
2
3 private static final long serialVersionUID = 1339434510787399891L;
4 private Long id;
5
6 private String username;
7
8 private String password;
9
10 public User() {
11 }
12
13 public User(Long id, String username, String password) {
14 this.id = id;
15 this.username = username;
16 this.password = password;
17 }
18
19 public Long getId() {
20 return id;
21 }
22
23 public void setId(Long id) {
24 this.id = id;
25 }
26
27 public String getUsername() {
28 return username;
29 }
30
31 public void setUsername(String username) {
32 this.username = username;
33 }
34
35 public String getPassword() {
36 return password;
37 }
38
39 public void setPassword(String password) {
40 this.password = password;
41 }
42
43 @Override
44 public String toString() {
45 return "User{" +
46 "id=" + id +
47 ", username='" + username + '\'' +
48 ", password='" + password + '\'' +
49 '}';
50 }
51}
52
53
创建一个SpringBoot项目,名字:ribbon-consumer项目结构:
pom.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64 1<?xml version="1.0" encoding="UTF-8"?>
2<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4 <modelVersion>4.0.0</modelVersion>
5
6 <groupId>com.zlx</groupId>
7 <artifactId>Ribbon-Consumer</artifactId>
8 <version>0.0.1-SNAPSHOT</version>
9 <packaging>jar</packaging>
10
11 <name>Ribbon-Consumer</name>
12 <description>Demo project for Spring Boot</description>
13
14 <parent>
15 <groupId>org.springframework.boot</groupId>
16 <artifactId>spring-boot-starter-parent</artifactId>
17 <version>1.5.13.RELEASE</version>
18 <relativePath/> <!-- lookup parent from repository -->
19 </parent>
20
21 <properties>
22 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
23 <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
24 <java.version>1.8</java.version>
25 </properties>
26
27 <dependencyManagement>
28 <dependencies>
29 <dependency>
30 <groupId>org.springframework.cloud</groupId>
31 <artifactId>spring-cloud-dependencies</artifactId>
32 <version>Edgware.SR3</version>
33 <type>pom</type>
34 <scope>import</scope>
35 </dependency>
36 </dependencies>
37 </dependencyManagement>
38 <dependencies>
39 <dependency>
40 <groupId>org.springframework.cloud</groupId>
41 <artifactId>spring-cloud-starter-eureka</artifactId>
42 </dependency>
43 <dependency>
44 <groupId>org.springframework.boot</groupId>
45 <artifactId>spring-boot-starter</artifactId>
46 </dependency>
47 <dependency>
48 <groupId>org.springframework.cloud</groupId>
49 <artifactId>spring-cloud-starter-ribbon</artifactId>
50 </dependency>
51 </dependencies>
52
53 <build>
54 <plugins>
55 <plugin>
56 <groupId>org.springframework.boot</groupId>
57 <artifactId>spring-boot-maven-plugin</artifactId>
58 </plugin>
59 </plugins>
60 </build>
61
62</project>
63
64
然后编写启动类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 1@EnableDiscoveryClient
2@SpringBootApplication
3public class RibbonConsumerApplication {
4 @Bean
5 @LoadBalanced
6 RestTemplate restTemplate() {
7 return new RestTemplate();
8 }
9 public static void main(String[] args) {
10 SpringApplication.run(RibbonConsumerApplication.class, args);
11 }
12
13}
14
15
application.yml
1
2
3
4
5
6
7
8
9
10
11
12
13
14 1server:
2 port: 9000
3
4spring:
5 application:
6 name: Server-Consumer
7
8eureka:
9 client:
10 serviceUrl:
11 defaultZone: http://root:root@peer1:80/eureka/,http://root:root@peer2:81/eureka/
12
13
14
User类:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51 1public class User implements Serializable {
2
3 private static final long serialVersionUID = 1339434510787399891L;
4 private Long id;
5 private String username;
6 private String password;
7
8 public User() {
9 }
10
11 public User(Long id, String username, String password) {
12 this.id = id;
13 this.username = username;
14 this.password = password;
15 }
16
17 public Long getId() {
18 return id;
19 }
20
21 public void setId(Long id) {
22 this.id = id;
23 }
24
25 public String getUsername() {
26 return username;
27 }
28
29 public void setUsername(String username) {
30 this.username = username;
31 }
32
33 public String getPassword() {
34 return password;
35 }
36
37 public void setPassword(String password) {
38 this.password = password;
39 }
40
41 @Override
42 public String toString() {
43 return "User{" +
44 "id=" + id +
45 ", username='" + username + '\'' +
46 ", password='" + password + '\'' +
47 '}';
48 }
49}
50
51
TestController类:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46 1@RestController
2public class TestController {
3
4 @Autowired
5 private RestTemplate restTemplate;
6
7 @GetMapping("user/{id:\\d+}")
8 public User getUser(@PathVariable Long id) {
9 Map<String, Object> params = new HashMap<>();
10 params.put("id", id);
11 URI uri = UriComponentsBuilder.fromUriString("http://Server-Provider/user/{id}")
12 .build().expand(params).encode().toUri();
13 return this.restTemplate.getForEntity(uri, User.class).getBody();
14 }
15
16 @GetMapping("user")
17 public List<User> getUsers() {
18 return this.restTemplate.getForObject("http://Server-Provider/user", List.class);
19 }
20
21 @GetMapping("user/add")
22 public String addUser() {
23 User user = new User(1L, "mrbird", "123456");
24 HttpStatus status = this.restTemplate.postForEntity("http://Server-Provider/user", user, null).getStatusCode();
25 if (status.is2xxSuccessful()) {
26 return "新增用户成功";
27 } else {
28 return "新增用户失败";
29 }
30 }
31
32 @GetMapping("user/update")
33 public void updateUser() {
34 User user = new User(1L, "mrbird", "123456");
35 this.restTemplate.put("http://Server-Provider/user", user);
36 }
37
38 @GetMapping("user/delete/{id:\\d+}")
39 public void deleteUser(@PathVariable Long id) {
40 this.restTemplate.delete("http://Server-Provider/user/{1}", id);
41 }
42}
43
44
45
46
发送Get请求
RestTemplate中与GET请求对应的方法有getForEntity和getForObject。
getForEntity
getForEntity方法返回ResponseEntity对象,该对象包含了返回报文头,报文体和状态码等信息。getForEntity有三个重载方法:
- getForEntity(String url, Class responseType, Object…uriVariables);
- getForEntity(String url, Class responseType,Map<String, ?> uriVariables);
- getForEntity(URI url, Class responseType);
第一个参数为Url,第二个参数为返回值的类型,第三个参数为请求的参数(可以是数组,也可以是Map)。
在Testcontroller中举个getForEntity(String url, Class<.T> responseType, Object… uriVariables)的使用例子:
1
2
3
4
5
6 1@GetMapping("user/{id:\\d+}")
2public User getUser(@PathVariable Long id) {
3 return this.restTemplate.getForEntity("http://Server-Provider/user/{name}", User.class, id).getBody();
4}
5
6
{1}为参数的占位符,匹配参数数组的第一个元素。因为第二个参数指定了类型为User,所以调用getBody方法返回类型也为User。
方法参数除了可以放在数组里外,也可以放在Map里,举个getForEntity(String url, Class<T.> responseType, Map<String, ?> uriVariables)使用例子:
1
2
3
4
5
6
7
8 1@GetMapping("user/{id:\\d+}")
2public User getUser(@PathVariable Long id) {
3 Map<String, Object> params = new HashMap<>();
4 params.put("id", id);
5 return this.restTemplate.getForEntity("http://Server-Provider/user/{id}", User.class, params).getBody();
6}
7
8
只有两个参数的重载方法getForEntity(URI url, Class<.T> responseType)第一个参数接收java.net.URI类型,可以通过org.springframework.web.util.UriComponentsBuilder来创建,举个该方法的使用例子:
1
2
3
4
5
6
7
8
9
10 1@GetMapping("user/{id:\\d+}")
2public User getUser(@PathVariable Long id) {
3 Map<String, Object> params = new HashMap<>();
4 params.put("id", id);
5 URI uri = UriComponentsBuilder.fromUriString("http://Server-Provider/user/{id}")
6 .build().expand(params).encode().toUri();
7 return this.restTemplate.getForEntity(uri, User.class).getBody();
8}
9
10
其中expand方法也可以接收数组和Map两种类型的参数。
getForObject
getForObject方法和getForEntity方法类似,getForObject方法相当于getForEntity方法调用了getBody方法,直接返回结果对象,为不是ResponseEntity对象。
getForObject方法和getForEntity方法一样,也有三个重载方法,参数类型和getForEntity方法一致,所以不再列出。
发送POST请求
使用RestTemplate发送PUT请求,使用的是它的put方法,put方法返回值是void类型,该方法也有三个重载方法:
-
put(String url, Object request, Object… uriVariables);
-
put(String url, Object request, Map<String, ?> uriVariables);
-
put(URI url, Object request)。
1
2
3
4
5
6
7 1@GetMapping("user/update")
2public void updateUser() throws JsonProcessingException {
3 User user = new User(1L, "mrbird", "123456");
4 this.restTemplate.put("http://Server-Provider/user", user);
5}
6
7
在RESTful风格的接口中,判断成功失败不再是通过返回值的某个标识来判断的,而是通过返回报文的状态码是否为200来判断。当这个方法成功执行并返回时,返回报文状态为200,即可判断方法执行成功。
发送DELETE请求
使用RestTemplate发送DELETE请求,使用的是它的delete方法,delete方法返回值是void类型,该方法也有三个重载方法:
-
delete(String url, Object… uriVariables);
-
delete(String url, Map<String, ?> uriVariables);
-
delete(URI url)。
1
2
3
4
5
6 1@GetMapping("user/delete/{id:\\d+}")
2public void deleteUser(@PathVariable Long id) {
3 this.restTemplate.delete("http://Server-Provider/user/{1}", id);
4}
5
6
我们分别启动两个Eureka Server用于集群,Eureka Client实例,然后启动Ribbon-Consumer。
访问http://localhost:9000/user/1(后面每个方法我们都访问两次,用于观察负载均衡),返回结果如下:
Spring Cloud Ribbon配置
Spring Cloud Ribbon的配置分为全局和指定服务名称。比如我要指定全局的服务请求连接超时时间为200毫秒:
1
2
3
4 1ribbon:
2 ConnectTimeout: 200
3
4
如果只是设置获取Server Provider服务的请求连接超时时间,我们只需要在配置最前面加上服务名称就行了,如:
1
2
3
4
5 1Server-Provider:
2 ribbon:
3 ConnectTimeout: 200
4
5
设置获取Server-Provider服务的负载均衡算法从轮询改为随机:
1
2
3
4
5 1Server-Provider:
2 ribbon:
3 NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
4
5
设置处理Server-Provider服务的超时时间:
1
2
3
4
5 1Server-Provider:
2 ribbon:
3 ReadTimeout: 1000
4
5
开启重试机制,即获取服务失败是否从另外一个节点重试,默认值为false:
1
2
3
4
5
6
7 1spring:
2 cloud:
3 loadbalancer:
4 retry:
5 enabled: true
6
7
对Server-Provider的所有请求在失败的时候都进行重试:
1
2
3
4
5
6 1Server-Provider:
2 ribbon:
3 OkToRetryOnAllOperations: true
4
5
6
切换Server-Provider实例的重试次数:
1
2
3
4
5 1Server-Provider:
2 ribbon:
3 MaxAutoRetriesNextServer: 1
4
5
对Server-Provider当前实例的重试次数:
1
2
3
4
5
6 1Server-Provider:
2 ribbon:
3 MaxAutoRetries: 1
4
5
6
根据如上配置当访问Server-Provider服务实例(比如是82)遇到故障的时候,Ribbon会再尝试访问一次当前实例(次数由MaxAutoRetries配置),如果不行,就换到83实例进行访问(更换次数由 MaxAutoRetriesNextServer决定),如果还是不行,那就GG思密达,返回失败。
如果不和Eureka搭配使用的话,我们就需要手动指定服务清单给Ribbon:
1
2
3
4
5 1Server-Provider:
2 ribbon:
3 listOfServers: localhost:82,localhost:83
4
5