概述
Ribbon
Ribbon主要用于负载均衡,注册中心Eureka中包含Ribbon依赖,可以在客户端注入新的带有负载均衡的RestTemplate对象到容器中。
用法如下:
@Configuration
public class ApplicationContextConfig {
@Bean
@LoadBalanced
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
Feign
Feign主要用于做服务调用,通常在客户端将服务端的所有请求封装成一个微服务调用接口,然后注入到容器中,给Controller层做调用。
用法如下:
@Component
@FeignClient(value = "微服务名")
public interface Service {
/**
* 该方法请求方式、路径及方法须与服务端Controller接口保持一致
*/
@GetMapping("/a/b/c")
ReturnType methodName(int i);
}
Hystrix
Hystrix主要用于做服务降级、服务熔断及服务限流。
微服务Ribbon、Feign及Hystrix服务降级的区别
- Feign默认引入Ribbon,当使用Feign做服务调用时,使用Feign或Hystrix做服务降级时需指定Ribbon超时时间,否则可能因为Ribbon默认的超时时间为1秒而发生服务降级。
application.yml配置如下:
ribbon:
# 指的是建立连接后从服务器读取到可用资源所用的时间
ReadTimeout: 5000
# 指的是建立连接所用的时间,适用于网络状况正常的情况下,两端连接所用的时间
ConnectTimeout: 5000
- 使用Hystrix做服务降级
@RestController
@DefaultProperties(defaultFallback = "global_FallbackMethod", commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",
value = "2000")}) // 配置Hystrix全局服务降级方法
public class Controller {
/**
* 业务方法一
*/
@GetMapping("/payment/hystrix/timeout/{id}")
@HystrixCommand(fallbackMethod = "fallbackMethod", commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",
value = "3000")}) // 该注解指定了服务降级时所调用的fallback方法
@GetMapping("/a/b/c")
ReturnType methodOne(int i){
// 方法体;
}
/**
* 业务方法二
*/
@GetMapping("/a/b/d")
@HystrixCommand // 该注解不指定fallback方法,默认使用全局降级方法
ReturnType methodTwo(int i){
// 方法体;
}
/**
* fallback方法一
*/
ReturnType fallbackMethod(int i){
// 方法体;
}
/**
* 全局fallback方法
*/
ReturnType global_FallbackMethod(int i){
// 方法体;
}
- 使用Feign做服务降级(Fegin对Hystrix做了封装)
- application.yml开启服务降级,配置如下:
feign:
hystrix:
enabled: true # 开启服务降级
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 5000 # 指定超时时间
- 定义一个服务降级类继承Feign服务调用接口,并实现对应服务降级方法
/**
* 服务降级类
*/
@Component
public class FallbackService implements FeignService{
@Override
public int a() {
// 服务降级处理;
}
}
- Feign服务调用接口添加fallback需要调的服务降级处理类
@Component
@FeignClient(value = "微服务名",fallback = FallbackService.class) // fallback指定服务降级处理类
public interface FeignService {
@GetMapping("/a/b/c")
public int a();
}
- 注意:当同时使用Fegin和Hystrix做降级处理时,需要设置Feign超时时间,否则可能因为Fegin默认超时时间1秒而导致其他方法服务发生降级。(原因:Ribbon、Feign和Hystrix降级同时工作时取三者最小超时时间)。
评论区