SpringCloud入门之使用OpenFeign支持的Hystrix,对异常服务快速响应


前言

如果想在服务中加入一种中断异常服务并可以快速响应的功能的话,使用Feign集成的Hystrix是一个还不错的选择。


一、OpenFeign对Hystrix的支持

要让hystrix生效,需要开启feign.hyxtrix。开启了feign.hystrix之后,feign就会用断路器包裹所有的方法,对这些方法起保护作用,通过回退方法把异常信息反馈回去。

二、配置

1. yml的配置

1.1 启用feign的hystrix,令其生效

feign:
  hystrix:
    enabled: true

1.2 在配置一下超时

hystrix:
  command:
    default:
      execution:
        timeout:
          enabled: true
        isolation:
          thread:
            timeoutInMilliseconds: 60000

2. Hystrix的回退

hystrix的回退有两种一种是带异常信息的,一种是不带异常信息的。对于这种不带异常信息的应该用的不多,下边的示例是带有异常信息的。

代码如下(示例):

import com.test.backend.common.domain.CommonResult;
import com.test.backend.common.domain.Payment;
import com.test.springcloud.feign.api.PaymentServiceFeign;
import feign.FeignException;
import feign.RetryableException;
import feign.hystrix.FallbackFactory;
import org.springframework.stereotype.Component;

@Component
public class PaymentServiceFeignFallbackFactory implements FallbackFactory<PaymentServiceFeign> {
    @Override
    public PaymentServiceFeign create(Throwable throwable) {
        return new PaymentServiceFeign() {
            @Override
            public CommonResult<Payment> getPaymentById() {
                CommonResult commonResult = new CommonResult();
                commonResult.setMsg(throwable.getMessage());
                // 对方服务没启动
                if (throwable instanceof FeignException.ServiceUnavailable) {
                    System.out.println("对方服务不可用");
                    // 对方服务报错了
                } else if (throwable instanceof FeignException.InternalServerError){
                    System.out.println("对方服务内部异常");
                    // 对方服务启后又关了
                }else if( throwable instanceof RetryableException) {
                    System.out.println("对方服务重试后无法连接");
                }
                return commonResult;
            }
        };
    }
}

回退类编写完毕后,需要在FeignClient上配置一下

@FeignClient(value = "backend-service", contextId = "backend-service-1", fallbackFactory = PaymentServiceFeignFallbackFactory.class)

三、 效果

emmmm,好像也没啥可以展示的效果图,自己写写代码感受感受就完事了。


总结

feign提供的Hystix断路保护功能,能够大大的提升了服务的稳定性,毕竟没那么多的异常了,当使用feign访问的远程服务有异常时,通过回退类做一些明确的响应提示或者其他的处理还是挺不错的。
印象中Hystrix有个单独的包,还有挺多的参数,有空在研究一下…

  • 6
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值