服务熔断—服务提供者
@RestController
public class EmployeeHandler {
// @HystrixCommand注解指定当前方法出问题时调用的备份方法(使用fallbackMethod属性指定)
@HystrixCommand(fallbackMethod = "getEmpWithCircuitBreakerBackup")
@RequestMapping("/provider/get/emp/with/circuit/breaker")
public ResultEntity<Employee> getEmpWithCircuitBreaker(@RequestParam("signal") String signal) throws InterruptedException {
if("quick-bang".equals(signal)) {
throw new RuntimeException();
}
if("slow-bang".equals(signal)) {
Thread.sleep(5000);
}
return ResultEntity.successWithData(new Employee(666, "empName666", 666.66));
}
// 熔断处理方法
public ResultEntity<Employee> getEmpWithCircuitBreakerBackup(@RequestParam("signal") String signal) {
String message = "方法执行出现问题,执行断路 signal="+signal;
return ResultEntity.failed(message);
}
}
服务降级—服务消费者者
远程接口映射
// @FeignClient注解表示当前接口和一个Provider对应
// 注解中value属性指定要调用的Provider的微服务名称
// 注解中fallbackFactory属性指定Provider不可用时提供备用方案的工厂类型
@FeignClient(value = "atguigu-provider", fallbackFactory = MyFallBackFactory.class)
public interface EmployeeRemoteService {
// 远程调用的接口方法
// 要求@RequestMapping注解映射的地址一致
// 要求方法声明一致
// 用来获取请求参数的@RequestParam、@PathVariable、@RequestBody不能省略,两边一致
@RequestMapping("/provider/get/employee/remote")
public Employee getEmployeeRemote();
@RequestMapping("/provider/get/emp/list/remote")
public List<Employee> getEmpListRemote(String keyword);
@RequestMapping("/provider/get/emp/with/circuit/breaker")
public ResultEntity<Employee> getEmpWithCircuitBreaker(@RequestParam("signal") String signal);
}
降级处理方法
/**
* 1.实现Consumer端服务降级功能
* 2.实现FallbackFactory接口时要传入@FeignClient注解标记的接口类型
* 3.在create()方法中返回@FeignClient注解标记的接口类型的对象,当Provider调用失败后,会执行这个对象的对应方法
* 4.这个类必须使用@Component注解将当前类的对象加入IOC容器,当然当前类必须能够被扫描到
*
*/
@Component
public class MyFallBackFactory implements FallbackFactory<EmployeeRemoteService> {
@Override
public EmployeeRemoteService create(Throwable cause) {
return new EmployeeRemoteService() {
@Override
public Employee getEmployeeRemote() {
return null;
}
@Override
public ResultEntity<Employee> getEmpWithCircuitBreaker(String signal) {
return ResultEntity.failed("降级机制生效:" + cause.getMessage());
}
@Override
public List<Employee> getEmpListRemote(String keyword) {
return null;
}
};
}
}