场景
SpringCloud中集成Hystrix实现服务降级(从实例入手):
SpringCloud中集成Hystrix实现服务降级(从实例入手)_霸道流氓气质的博客-CSDN博客
上面在进行降级配置的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。
注:
博客:
霸道流氓气质的博客_CSDN博客-C#,架构之路,SpringBoot领域博主
关注公众号
霸道的程序猿
获取编程相关电子书、教程推送与免费下载。
实现
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关掉,模拟宕机的情况,此时服务消费者中调用对应的服务则会进入对应的实现中的返回。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/135949.html