我是在springcloud中使用的hystrix。
熔断机制:在服务提供者(provider)使用,某个控制器方法出现问题了之后去调用备用方法。
使用步骤:
(1)首先,使用熔断要在启动入口配置@EnableCircuitBreaker启动熔断机制。
(2)使用@HystrixCommand放在某个控制器方法上,当这个方法内部出现问题而无法正常使用时,会去调用HystrixCommand注解中fallbackMethod属性所指定的方法,在下面代码中,指定了备用方法为listFallback。
@HystrixCommand(fallbackMethod = "listFallback")
@GetMapping(value = "/dept/list/{tableName}")
public List<Dept> list(@PathVariable("tableName") String tableName) {
if(tableName.equals("熔断")){
throw new RuntimeException("故意熔断");
}
ArrayList<Dept> depts = new ArrayList<>();
Dept dept = new Dept();
dept.setDname("表名:"+tableName);
depts.add(dept);
return depts;
}
public List<Dept> listFallback(@PathVariable("tableName") String tableName) {
ArrayList<Dept> depts = new ArrayList<>();
Dept dept = new Dept();
dept.setDname("熔断乐乐乐乐乐乐乐乐乐");
depts.add(dept);
return depts;
}
服务降级:是使用在消费者(consumer)端,与feign一起使用的,当FeignClient调用其他服务时,被调用服务出现问题了,则转而调用备用服务。
使用步骤:
(1) 在yml配置文件中启动hystrix,添加如下配置:
feign:
hystrix:
enabled: true
(2)FeignClient接口上使用@FeignClient注解使用value属性指定要调用哪个服务,而服务降级备用逻辑使用fallbackFactory属性指定一个后备调用工厂类(下面代码中的DeptClientServiceFallbackFactory)。
代码如下
@FeignClient(value = "spring-cloud-dept",fallbackFactory = DeptClientServiceFallbackFactory.class)
public interface DeptClientService {
@GetMapping(value = "/dept/list/{tableName}")
List<Dept> list(@PathVariable("tableName") String tableName);
}
(3)这个后备调用工厂类需要实现FallbackFactory接口,FallbackFactory接口需要指定个泛型类型,这个泛型类型就是后备调用方法的接口了,这里就是DeptClientService接口(就上面那段代码)。
经过测试,FallbackFactory的泛型接口必须是FeignClient接口。
比如DeptClientService 是FeignClient接口,DeptClientService 的@FeignClient注解的fallbackFactory 指定的后备工厂类的泛型必须是DeptClientService
后备调用工厂类定义如下:
@Component
public class DeptClientServiceFallbackFactory implements FallbackFactory<DeptClientService> {
@Override
public DeptClientService create(Throwable throwable) {
return new DeptClientServiceFallbackFactory () {
@Override
public List<Dept> list(String tableName) {
List<Dept> list = new ArrayList<>();
Dept dept = new Dept();
dept.setDname("出现问题了,此刻返回熔断错误信息");
list.add(dept);
return list;
}
};
}
}
(4)当前服务控制器注入Feign客户端调用接口DeptClientService后,调用DeptClientService里面的方法时不是会通过ribbon去调用其他相应微服务的接口么,当被调用的微服务崩了,此时DeptClientService就会转而去调用DeptClientServiceFallbackFactory 后备工厂类中的create方法创造出来的DeptClientService类型的实例中的相应方法(也就是上面那段代码中匿名内部类的list方法就是备用方法。)
(5)注意,一定要把DeptClientServiceFallbackFactory扫描成为bean,即添加注解@Component,否则出问题。
总结,服务降级与Feign一起使用时,Feign客户端接口调用其他微服务时,其他微服务崩了,此时Feign客户端接口会调用fallbackFactory属性指定的后备工厂类所生产的后备调用类实例的方法。