场景
上面在进行降级配置的fallback时是通过如下方式配置
@GetMapping("/consumer/payment/hystrix/timeout/{id}")
@HystrixCommand(fallbackMethod = "paymentInfo_TimeOutHandler",commandProperties = { @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="2000")
})
public String paymentInfo_TimeOut(Integer id)
{
//int age = 10/0;
String result = paymentHystrixService.paymentInfo_TimeOut(id);
return result;
}
public String paymentInfo_TimeOutHandler(Integer id)
{
return "线程池: "+Thread.currentThread().getName()+"来自消费者88的提示:服务提供者繁忙或者运行报错,请稍后再试,id: "+id+"\t"+"o(╥﹏╥)o";
}
但是这样就需要在每个方法中重复添加注解并配置fallback方法。
有没有可以通配的方式进行配置fallback。
注:
关注公众号
霸道的程序猿
获取编程相关电子书、教程推送与免费下载。
实现
1、首先确保yml中如下配置已经打开
feign:
hystrix:
enabled: true
2、然后新建一个类实现上面的Service接口,统一为接口里面的方法进行异常处理
package com.badao.springclouddemo.service;
import org.springframework.stereotype.Component;
@Component
public class PaymentFallbackService implements PaymentHystrixService
{
@Override
public String paymentInfo_OK(Integer id)
{
return "-----PaymentFallbackService fall back-paymentInfo_OK ,o(╥﹏╥)o";
}
@Override
public String paymentInfo_TimeOut(Integer id)
{
return "-----PaymentFallbackService fall back-paymentInfo_TimeOut ,o(╥﹏╥)o";
}
}
3、给service接口中@FeignClinet注解中配置fallback属性为上面的实现类
package com.badao.springclouddemo.service;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@Component
@FeignClient(value = "CLOUD-PROVIDER-HYSTRIX-PAYMENT",fallback = PaymentFallbackService.class)
public interface PaymentHystrixService
{
@GetMapping("/payment/hystrix/ok/{id}")
public String paymentInfo_OK(@PathVariable("id") Integer id);
@GetMapping("/payment/hystrix/timeout/{id}")
public String paymentInfo_TimeOut(@PathVariable("id") Integer id);
}
4、此时依次启动Eureka Server 7001,以及服务提供者8001和服务消费者88
正常访问服务确保没问题
然后将8001关掉,模拟宕机的情况,此时服务消费者中调用对应的服务则会进入对应的实现中的返回。