美文网首页
SpringCloud学习(二)之Ribbon

SpringCloud学习(二)之Ribbon

作者: Gukson666 | 来源:发表于2019-11-28 21:40 被阅读0次

    Ribbon简介

    在微服务架构中,业务都会被拆分成一个独立的服务,服务与服务的通讯是基于Http Restful的。SpringCloud有两种服务调用方式,一种是Ribbon + RestTemplate,另一种是Feign。Ribbon是一个负载均衡客户端,可以很好的控制http和tcp的一些行为。Feign默认集成了Ribbon。

    1. 引入依赖:
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-ribbon</artifactId>
    </dependency>
    
    1. 通过@EnableDiscoveryClient向服务中心注册:
    @SpringBootApplication
    @EnableDiscoveryClient
    public class ServiceRibbonApplication {
        public static void main(String[] args) {
            SpringApplication.run(ServiceRibbonApplication.class, args);
        }
        @Bean
        @LoadBalanced
        RestTemplate restTemplate() {
            return new RestTemplate();
        }
    }
    

    向程序的ioc注入一个bean: restTemplate;并通过@LoadBalanced注解表明这个restRemplate开启负载均衡的功能。

    1. 配置文件application.yml如下:
    eureka:
      client:
        serviceUrl:
          defaultZone: http://localhost:8761/eureka/
    server:
      port: 8764
    spring:
      application:
        name: service-ribbon
    

    启动工程后,可以在 http://localhost:8761/ 中看到service-ribbon注册进来了。

    负载均衡测试:

    1. 复制一个上篇文章中端口为8762的微服务service-1,将端口改为8763启动,此时可以在注册表中看到有两个service-1实例。
    2. 接下来通过之前注入IOC容器的restTemplate来消费service-1服务的接口,我们可以用的程序名替代具体的URL地址,在Ribbon中会根据服务名来选择具体的服务实例,根据服务实例在请求的时候会用具体的url替换掉服务名。
    3. 在浏览器上多次访问http://localhost:8764/{yourInterface}就会出现启动的两个service-1实例会被轮流调用,这就说明进行了负载均衡,访问了不同的端口的服务实例。

    相关文章

      网友评论

          本文标题:SpringCloud学习(二)之Ribbon

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