Ribbon 负载均衡服务调用
5.1 Ribbon简介
Spring Cloud Ribbon是一个基于HTTP和TCP的客户端负载均衡工具,它基于Netflix Ribbon实现。通过Spring Cloud的封装,可以让我们轻松地将面向服务的REST模版请求自动转换成客户端负载均衡的服务调用。
5.2 Ribbon 内置负载均衡算法
RoundRobinRule | 轮询规则 |
---|---|
RandomRule | 随机轮询 |
RetryRule | 先按照RoundRobinRule获取服务,如果获取失败就在指定实现内重试。 |
WeightedResponseTimeRule | 对RoundRobinRule的扩展,响应速度越快的实例选择权重越大。 |
BestAvailableRule | 会先过滤掉因为多次访问故障而处于断路器跳闸状态的服务,然后选择一个并发量最小的服务 |
AvailabilityFilteringRule | 先过滤掉故障实例,再选择并发较小的实例 |
ZoneAvoidanceRule | 默认规则,复合判断server所在区域的性能和server的可用性选择服务器。 |
OpenFeign
6.1 OpenFeign简介:
Feign是声明式的Web Service客户端,它让微服务之间的调用变得更简单了,它能够类似Controller的方式调用Service。
Spring Cloud集成了Ribbon和Eureka,可使用基于Feign且提供负载均衡的HTTP客户端。
6.2 OpenFeign使用步骤
-
新建Cloud-Consumer-Order-Feign-80项目
-
加入OpenFeign的Dependency
org.springframework.cloud spring-cloud-starter-openfeign 3.0.0 -
在启动类上使用 @EnableFeignClients 注解
-
编写OpenFeign的Service类并添加 @FeignClient 注解
@Service @FeignClient("cloud-payment-service") public interface PaymentFeignService { @GetMapping(value = "/payment/get/{id}") JsonResponse
getPaymentById(@PathVariable("id") Long id); } -
编写Controller,直接调用Service即可
@RestController @Slf4j public class OrderController { // private static final String PAYMENT_URL = "http://localhost:8001"; private static final String PAYMENT_URL = "http://cloud-payment-service"; private final PaymentFeignService paymentFeignService; public OrderController(PaymentFeignService paymentFeignService) { this.paymentFeignService = paymentFeignService; } @GetMapping("/consumer/payment/get/{id}") public JsonResponse
getPayment(@PathVariable("id") Long id) { return paymentFeignService.getPaymentById(id); } }
文章评论