Ribbon——负载均衡

1 Ribbon简介

Ribbon是Netflix发布的基于HTTP和TCP的客户端负载均衡器,为Ribbon配置服务提供者的地址列表后,Ribbon就可以基于某种负载均衡算法,自动地帮助服务消费者去请求。在Spring Cloud 中, 当Ribbon与Eureka配合使用时,Ribbon可以自动从Eureka Server中获取服务提供者地址列表,并基于负载均衡算法,请求其中一个服务提供者实例。

2 Eureka整合Ribbon

  1. 添加相应的依赖:
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.cloud
            spring-cloud-starter-eureka
        
        
            org.springframework.cloud
            spring-cloud-starter-ribbon
        
  1. 服务消费者也是一个Eureka Client,同样需要声明@EnableDiscoveryClient,另外需要初始化RestTemplate,添加@LoadBalanced实现负载均衡
@EnableDiscoveryClient
@SpringBootApplication
public class RibbonDemoApplication {

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



    public static void main(String[] args) {
        SpringApplication.run(RibbonDemoApplication.class, args);
    }
}

在这里已经整合完毕,这时为我们就可以用微服务的虚拟主机名请求微服务。

  1. 调用微服务
@RestController
public class Controller {


    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/hello")
    public String hello() {

        return this.restTemplate.getForObject("http://eureka-client-demo/hello", String.class);
    }
}

在这里,我们调用eureka-client-demo服务的/hello接口时,直接使用了它的虚拟主机名,Ribbon会自动将虚拟主机名映射为微服务的网络地址。

参考:《Spring Cloud与Docker微服务架构实战》周立 著

你可能感兴趣的:(Ribbon——负载均衡)