服务熔断是指当服务访问频繁被拒绝后会调用服务降级的fallbackMethod方法拒绝访问, 当过一段时间后会进入半开状态先允许一部分请求进行访问如果可以则调整为全开状态
1.主启动
@SpringBootApplication
@EnableEurekaClient
@EnableCircuitBreaker
public class PaymentHystrixMain8001 {
public static void main(String[] args) {
SpringApplication.run(PaymentHystrixMain8001.class,args);
}
}
二、service层
@Service
public class PaymentService {
public String paymentInfo_OK(Integer id){
return "线程池: "+Thread.currentThread().getName()+" paymentInfo_OK,id: "+id+"\t"+"O(∩_∩)O哈哈";
}
@HystrixCommand(fallbackMethod = "paymentInfo_TimeOutHandler",commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "5000")
})
public String paymentInfo_TimeOut(Integer id){
int timenumbe=3000;
// int age=10/0;
try {
TimeUnit.MILLISECONDS.sleep(timenumbe);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "线程池: "+Thread.currentThread().getName()+" paymentInfo_TimeOut,id: "+id+"\t"+"O(∩_∩)O哈哈"+"耗时(毫秒 ): "+timenumbe;
}
public String paymentInfo_TimeOutHandler(Integer id){
return "线程池: "+Thread.currentThread().getName()+" 8001系统忙,请稍后再试,id: "+id+"\t"+"┭┮﹏┭┮";
}
//服务熔断
@HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback",commandProperties = {
@HystrixProperty(name = "circuitBreaker.enabled",value = "true"),//是否开启断路器
@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),//请求次数
@HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),//时间窗口
@HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"),//失败率达到多少后跳闸
})
public String paymentCircuitBreaker(@PathVariable("id") Integer id){
if (id<0){
throw new RuntimeException("**********id 不能负数");
}
String serialNumber=IdUtil.simpleUUID();//等价于UUID.randomUUID().toString()
return Thread.currentThread().getName()+"\t"+"调用成功,流水号: "+serialNumber;
}
public String paymentCircuitBreaker_fallback(@PathVariable("id") Integer id){
return "id 不能负数,请稍后再试,┭┮﹏┭┮ id: "+id;
}
}
三、controller
@RestController
@Slf4j
public class PaymentController {
@Resource
private PaymentService paymentService;
@Value("${server.port}")
private String serPort;
@GetMapping("/payment/hystrix/ok/{id}")
public String paymentInfo_OK(@PathVariable("id") Integer id){
String result=paymentService.paymentInfo_OK(id);
log.info("******result: "+result);
return result;
}
@GetMapping("/payment/hystrix/timeout/{id}")
public String paymentInfo_timeOut(@PathVariable("id") Integer id){
String result=paymentService.paymentInfo_TimeOut(id);
log.info("******result: "+result);
return result;
}
//===服务熔断
@GetMapping("/payment/circuit/{id}")
public String paymentCircuitBreaker(@PathVariable("id")Integer id){
String result=paymentService.paymentCircuitBreaker(id);
log.info("*******result: "+result);
return result;
}
}