springcloud微服务(十九) - Hystrix服务端和消费端的服务降级
程序员文章站
2022-03-15 13:37:12
...
一、服务端8002服务降级
降级配置:@HystrixCommand
(一)8002存在的问题:
设置自身调用超时时间的峰值,峰值内可以正常运行,超过了需要有兜底的方法处理,做服务降级fallback。
(二)、8002fallback
2.1 主启动类**
添加新注解@EnableHystrix,我们可以看到@EnableCircuitBreaker已经被标注删除线,但是@EnableHystrix集成了@EnableCircuitBreaker注解。
@SpringBootApplication
@EnableDiscoveryClient
@EnableHystrix
public class HystrixPayment8002 {
public static void main(String[] args)
{
SpringApplication.run(HystrixPayment8002.class,args);
}
}
2.2 在service的类上添加@HystrixCommand注解
@Service
public class HystrixPaymentService {
public String paymentInfo_ok(Integer id)
{
return "线程池:"+Thread.currentThread().getName()+" paymentInfo_ok,id="+id+"\t"+"成功";
}
//模拟业务流程长,耗时长
@HystrixCommand(fallbackMethod = "paymentInfo_timeouthandle",commandProperties = {
@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value = "3000")
})
public String paymentInfo_timeout(Integer id) {
int time=5;
try {
TimeUnit.SECONDS.sleep(time);
}catch (InterruptedException e)
{
e.printStackTrace();
}
return "线程池:"+Thread.currentThread().getName()+" paymentInfo_timeout,id="+id+"\t"+"超时";
}
public String paymentInfo_timeouthandle(Integer id) {
return "支付系统忙,请稍后再试";
}
}
注意:回退方法paymentInfo_timeouthandle必须与原方法的参数保持完全一致(参数个数与类型),否则会报错
com.netflix.hystrix.contrib.javanica.exception.FallbackDefinitionException: fallback method wasn't found
(三)、测试
请求http://127.0.0.1:8002/payment/info/timeout/667
3秒钟后会有收到应答,调用的回退函数生效。
(四)、异常时也会调用回退方法
二、客户端服务降级
(一)一般情况是客户端做服务降级,对客户端做保护
(二)主启动类加注解@EnableHystrix
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
@EnableHystrix
public class OpenFeignHystrixOrder80 {
public static void main(String[] args)
{
SpringApplication.run(OpenFeignHystrixOrder80.class,args);
}
}
(三)业务类加@HystrixCommand注解
@RestController
public class HystrixOrderController {
@Autowired
private HystrixPaymentService hystrixPaymentService;
@GetMapping("/consumer/payment/info/ok/{id}")
public String paymentInfo_ok(@PathVariable("id") Integer id)
{
return hystrixPaymentService.paymentInfo_ok(id);
}
//模拟业务流程长,耗时长
@GetMapping("/consumer/payment/info/timeout/{id}")
@HystrixCommand(fallbackMethod = "paymentInfo_timeoutFallback",commandProperties = {
@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="3000")
})
public String paymentInfo_timeout(@PathVariable("id") Integer id)
{
return hystrixPaymentService.paymentInfo_timeout(id);
}
public String paymentInfo_timeoutFallback(Integer id)
{
return "消费端80,支付系统异常,请稍后再试";
}
}
(四)测试
请求http://127.0.0.1/consumer/payment/info/timeout/667
3秒钟后会有收到应答,调用的回退函数生效。