美文网首页
Ribbon——负载均衡

Ribbon——负载均衡

作者: JacobY | 来源:发表于2018-01-14 03:12 被阅读0次

    1 Ribbon简介

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

    2 Eureka整合Ribbon

    1. 添加相应的依赖:
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-eureka</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-ribbon</artifactId>
            </dependency>
    
    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——负载均衡

          本文链接:https://www.haomeiwen.com/subject/vuohoxtx.html