记录一下在学习OpenFeign时使用Hystrix不生效问题(已解决)

最近在学习SpringCloud 在使用OpenFeign的Hystrix做熔断处理时fallback函数一直不生效

SpringCloud 环境

JDK 8
SpringCloud 2021.0.8
OpenFeign 3.1.8

一开始查资料,都是说OpenFeign集成了Hystrix需要手动开启Hystrix,添加以下配置:

feign:
	hystrix:
		enabled: true

但是我配置之后并没有生效,然后我就去看了我的OpenFeign依赖,发现并没有Hystrix。
通过查询资料发现在SpringCloud2020以后就不再支持Hystrix了,所以在后面的版本中OpenFeign并没有集成Hystrix了。需要手动添加依赖

<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
	<version>2.2.9.RELEASE</version>
</dependency>

application.yml中添加以下配置:

feign:
  circuitbreaker:
    enabled: true

@FeignClient设置fallback属性

@FeignClient(
        value = "hystrix-provider",
        fallback = LocalItemServiceImpl.class
)
@Primary
public interface LocalItemService {

    @RequestMapping(value = "/hi", method = RequestMethod.GET)
    public String hi(@RequestParam("id") String id);

}

因为Feign和Hystrix fallback一起使用时会导致@Autowired 注解不工作,所以需要通过@Primary 进行标注为主Bean
也可以在@Autowired上使用@Qualifier注解来指定

fallback的回调函数需要实现被@Feign修饰的接口,并且需要交给Spring容器管理

@Component
public class LocalItemServiceImpl implements LocalItemService {
    @Override
    public String hi(String id) {
        return String.format("bad %s", id);
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lJx~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值