首先声明:服务的熔断和降级是两个完全不同的概念,实现方式也不同。熔断是在服务的提供者那里,降级是在fegin那么远程调用的时候用的。
好了不多bb直接上熔断代码:
<!--熔断依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
代码:所用注解 @HystrixCommand(fallbackMethod = "getEmpBackup") fallbackMethod 是指熔断时候所用的方法
/*
* 服务的熔断是在服务提供方
* 降级是在消费方
*/
// @HystrixCommand 注解通过 fallbackMethod 属性指定断路情况下要调用的备份方法
@HystrixCommand(fallbackMethod = "getEmpBackup")
@RequestMapping("/provider/circuit/breaker/get/emp")
public ResultEntity<Employee> getEmp(@RequestParam("signal") String signal) {
if ("bang".equals(signal)) {
throw new RuntimeException();
}
return ResultEntity
.successWithData(new Employee(666, "sam666", 666.66));
}
public ResultEntity<Employee> getEmpBackup(
@RequestParam("signal") String signal) {
return ResultEntity.failed("circuit break workded,with signal="
+ signal);
}
好了熔断就是这么简单,不要忘记在启动类上加注解@EnableCircuitBreaker
@SpringBootApplication
@EnableCircuitBreaker
public class AtguiguMainType {
public static void main(String[] args) {
SpringApplication.run(AtguiguMainType.class, args);
}
}
接下来看降级: 降级是在远程调用的时候fegin、通常会把fegin单独抽离出来,就是为了好维护。
先加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
</dependencies>
写方法:
@Component
public class MyFallBackFactory implements
FallbackFactory<EmployeeRemoteService> {
/**
* cause是异常的原因
*
*/
@Override
public EmployeeRemoteService create(Throwable cause) {
return new EmployeeRemoteService() {
@Override
@RequestMapping("/provider/get/employee/remote")
public Employee getEmployeeRemote() {
return null;
}
@Override
@RequestMapping("/provider/get/employee/by/id")
public Employee getEmployeeById(Integer empId) {
return null;
}
@Override
@RequestMapping("/provider/save/emp")
public Employee saveEmp(Employee employee) {
return new Employee(444,
"call provider failed,fall back here, reason is "
+ cause.getClass().getName() + " "
+ cause.getMessage(), 444.444);
}
};
}
}
要想实现降级首先要实现 FallbackFactory<EmployeeRemoteService> 里面的类型填写你需要降级的远程调用类,
然后实现create方法,里面会重新你的接口的所有方法,在里面可以定义,在降级是返回给前端的各种。