Ribbon的使用

一、Ribbon是什么?

Ribbon是一个客户端负载均衡器。也就是说,在请求其他微服务的时候(集群),由Ribbon通过一些算法决定访问哪一个微服务。这些算法有:轮询算法(默认)、随机算法等。

二、如何使用Ribbon?

1、添加依赖(Eureka的依赖中已经包含了Ribbon)

<!--包含了Ribbon依赖-->
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

<!--在没有使用Eureka的情况下,可以单独添加-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>

 2、向Spring容器注入org.springframework.web.client.RestTemplate对象实例

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

说明:加了@LoadBalanced注解以后,使用restTemplate访问微服务时,具有负载均衡的能力了。以上的代码可以加在启动类上(@SpringBootApplication)或者加到@Configuration类上。

3、配置application.yml文件(注册到Eureka上即可)

server:
  port: 8010
spring:
  application:
    # 指定注册到eureka server上的服务名称
    name: ribbon-test

eureka:
  client:
    service-url:
      # 指定eureka server通信地址,注意/eureka/小尾巴不能少
      defaultZone: http://localhost:8761/eureka/

4、使用RestTemplate对象访问远程服务,完成访问。

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/users/{id}")
    public User findById(@PathVariable Long id) {
        // 这里用到了RestTemplate的占位符能力
        User user = this.restTemplate.getForObject(
"http://microserviceName/users/{id}", User.class, id);
        return user;
    }

说明:microserviceName是注册在Eureka上的Application Name,也就是微服务对外的名称。

 更详细的请查看官方文档:https://www.springcloud.cc/spring-cloud-dalston.html#spring-cloud-ribbon

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值