spring cloud实践(三) ribbon

Ribbon为我们提供了软负载均衡以及一定的容错处理。关于Ribbon的负载均衡与重试机制可参见客户端负载均衡以及服务容错(一) 重试

现在来实践一下:

  1. 服务端

在服务端添加接口:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@RestController
@RequestMapping("/hello")
public class HelloController {

...

@RequestMapping("/sleep")
public String sleep(){
try {
int time = ThreadLocalRandom.current().nextInt(6000);
log.info("call in will sleep: {}", time);
Thread.sleep(time);
return "port:" + config.getPort() + " sleep " + time;
} catch (InterruptedException e) {
e.printStackTrace();
}
return "port:" + config.getPort() + " sleep failed";
}
...
}

这里随机休眠了一段时间(小于6 s),并记录。然后启动三次本项目,端口分别配置在8998, 8999, 9000。

  1. 消费端

首先对消费端进行配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
hystrix:
command:
hello:
execution:
isolation:
thread:
timeoutInMilliseconds: 60000

spring-cloud-producer:
ribbon:
#NIWSServerListClassName: com.netflix.loadbalancer.ConfigurationBasedServerList
#NFLoadBalancerRuleClassName: com.netflix.loadbalancer.WeightedResponseTimeRule
ConnectTimeout: 1000 # 请求连接的超时时间
ReadTimeout: 1000 # 请求处理的超时时间
MaxTotalHttpConnections: 500 # 最大总连接数
MaxConnectionsPerHost: 100 # 单机连接最大数目
# 重试相关
MaxAutoRetries: 1 # 对当前实例的重试次数
MaxAutoRetriesNextServer: 3 # 切换实例的重试次数
OkToRetryOnAllOperations: true # 对所有操作请求都进行重试

因这里使用了Feign,所以在接口类新增方法:

1
2
3
4
5
6
7
8
@FeignClient(name = "spring-cloud-producer",
path = "/hello")
public interface HelloService {
...
@RequestMapping(value = "/sleep")
public String sleep();
...
}

在Controller新增:

1
2
3
4
5
6
7
8
9
@RestController
public class ConsumerController {
...
@RequestMapping("/sleep")
public String sleep(){
return helloService.sleep();
}
...
}
  1. 测试

启动消费者,访问 http://localhost:9001/sleep。

ribbon-test-web

注:这里结果是不确定的因为使用了随机数。

然后看console:

1
2
3
4
5
6
7
8
---------------------<端口号为9000的日志>-------------------------------
2019-03-18 16:05:10.462 INFO 11088 --- [nio-9000-exec-1] l.c.producer.controller.HelloController : call in will sleep: 5837
2019-03-18 16:05:11.484 INFO 11088 --- [nio-9000-exec-3] l.c.producer.controller.HelloController : call in will sleep: 2306
---------------------<端口号为8999的日志>-------------------------------
2019-03-18 16:05:12.484 INFO 11488 --- [nio-8999-exec-8] l.c.producer.controller.HelloController : call in will sleep: 3657
2019-03-18 16:05:13.489 INFO 11488 --- [nio-8999-exec-5] l.c.producer.controller.HelloController : call in will sleep: 3588
---------------------<端口号为8998的日志>--------------------------------
2019-03-18 16:05:14.491 INFO 12036 --- [nio-8998-exec-7] l.c.producer.controller.HelloController : call in will sleep: 27

在端口号为9000,和8999分别尝试了两次,然后再8998成功获取到数据。