最近在学习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);
}
}