1、在实现类实现熔断
1)、主启动类使用@EnableCircuitBreaker开启降级
@SpringBootApplication
@EnableFeignClients
@EnableCircuitBreaker
public class ServerShopWareApplication {
public static void main(String[] args) {
SpringApplication.run(ServerShopWareApplication.class, args);
}
}
2)、方法上使用@Hystrix注解
@Service
@Slf4j
public class IMessageService1Impl implements IMessageService1 {
public ResultResponse handleError(MessageVo messageVo) {
System.out.println("handleError:熔断了");
return ResultResponse.FAILED(500);
}
@Override
@HystrixCommand(
fallbackMethod = "handleError",
commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
})
public ResultResponse sendMessage(MessageVo messageVo) {
try {
for (int index = 0; index < 10; index++) {
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return ResultResponse.SUCCESS();
}
}
2、在接口上实现熔断
1)、application.properties配置文件添加配置
## 启动熔断器
feign.hystrix.enabled=true
2)、启动类添加@EnableHystrix
3)、方法使用@HystrixCommand
@PostMapping(value = "/msg1")
@HystrixCommand(
fallbackMethod = "handleError",
commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
})
public ResultResponse test1(@RequestParam("msg") String msg) {
MessageVo messageVo = new MessageVo();
messageVo.setId(IdWorker.getId());
messageVo.setType(1);
messageVo.setData(msg);
return iMessageService1.sendMessage(messageVo);
}
public ResultResponse handleError(@RequestParam("msg") String msg) {
System.out.println("handleError(controller):熔断了");
return ResultResponse.FAILED(404);
}
参考文档