[关闭]
@zero1036 2019-03-08T15:16:50.000000Z 字数 1784 阅读 1120

Spring-Ribbon与负载均衡

Java-Spring


PNG 图像.png-276.1kB

Ribbon是一个基于HTTP与TCP的客户端负载均衡器。

服务端列表去轮询访问以达到均衡负载的作用。当 Ribbon与 Eureka联合使用时, Ribbon 的服务实例清单 Ribbon Serverlist会被 Discoveryenabledniwsserverlist重写,扩展成从Eureka注册中心中获取服务端列表。同时它也会用 Niwsdiscoveryping来取代Ping,它将职责委托给Eureka来确定服务端是否已经启动。在本章中,我们对Ribbon不做详细的介绍,读者只需要理解它在Eureka服务发现的基础上,实现了一套对服务实例的选择策略,从而实现对服务的消费。下一章我们会对 Ribbon做详细的介绍和分析。

客户端示例:RestTemplate + Ribbon

  1. @SpringBootApplication
  2. @EnableDiscoveryClient
  3. @RestController
  4. public class RibbonClient {
  5. public static void main(String[] args) {
  6. SpringApplication.run(RibbonClient.class, args);
  7. }
  8. @Bean
  9. @LoadBalanced //实现负载均衡
  10. RestTemplate restTemplate() {
  11. return new RestTemplate();
  12. }
  13. @Autowired
  14. private RestTemplate restTemplate;
  15. @GetMapping("/ribbonInvoke")
  16. private String ribbonInvoke() {
  17. RibbonMessage msg = restTemplate.getForObject("http://TG-RIBBON-SERVICE/ribbonAccept", RibbonMessage.class);
  18. System.out.println(msg);
  19. return msg.toString();
  20. }
  21. }

调用后输出日志示例:

  1. 2019-02-01 16:15:53.953 INFO 11404 --- [nio-8201-exec-1] c.n.l.DynamicServerListLoadBalancer : DynamicServerListLoadBalancer for client TG-RIBBON-SERVICE initialized: DynamicServerListLoadBalancer:{NFLoadBalancer:name=TG-RIBBON-SERVICE,current list of Servers=[192.168.14.196:8056],Load balancer stats=Zone stats: {defaultzone=[Zone:defaultzone; Instance count:1; Active connections count: 0; Circuit breaker tripped count: 0; Active connections per server: 0.0;]
  2. },Server stats: [[Server:192.168.14.196:8056; Zone:defaultZone; Total Requests:0; Successive connection failure:0; Total blackout seconds:0; Last connection made:Thu Jan 01 08:00:00 CST 1970; First connection made: Thu Jan 01 08:00:00 CST 1970; Active Connections:0; total failure count in last (1000) msecs:0; average resp time:0.0; 90 percentile resp time:0.0; 95 percentile resp time:0.0; min resp time:0.0; max resp time:0.0; stddev resp time:0.0]
  3. ]}ServerList:org.springframework.cloud.netflix.ribbon.eureka.DomainExtractingServerList@53c23742
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注