SpringCloudFeginCircuit熔断失效原因
前言
今天想着给自己的微服务项目添加一个熔断的功能,正好项目内远程调用是用的feign,那就直接用hystrix好了,也比较方便。
然后呢,我以为比较简单的东西,却一直不生效,资料查了个遍,硬是弄了我一上午+一下午的时间,所以记录一下,给大家避坑。
当前环境
如果你的环境跟我差的有点多,那这篇文章可能对你的帮助不大。
- JDK8
- SpringBoot2.6.6
-
openfeign3.1.2 (是我写这篇文章时比较新的版本了)

不生效的原因
原因主要有二
-
配置文件
网上很多教程都是给的旧版本的配置文件,都是feign.hystrix.enabled: true,但在新版本这是不生效的 ,正确的配置应该是下面我这样:
feign: circuitbreaker: enabled: true可以参考官网文档:docs.spring.io/spring-clou…

-
引入依赖
网上很多教程说fegin集成了hystrix,可能旧版本确实集成了,但是新版本必须要手动添加依赖。不过这一点我没在官网上找到,
鬼知道官网为什么不写,害我找了半天,可能是我眼神不好。<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> <version>2.2.10.RELEASE</version> </dependency>
引用一位博主的话,我想说的也跟他差不多:
网上说的fegin集成hystrix误导人,害我以为添加的openfegin已经内置了hystrix,但实际是我找遍openfegin都没有看到hystrix依赖。所以需要自己添加hystrix依赖。
-
如果上面两个都不是的话,那你可能需要检查一下下面几个基本问题:
-
是否添加了 openfegin 的依赖
-
是否在启动类正确添加了@EnableFeignClients注解
-
或者你是否正确使用了@FeignClient的fallback参数
-
熔断处理的实现类是否有被Spring管控
以上差不多就是我想到的全部条件了。
-
附使用代码
ResourceClient.java:
package cn.sticki.resource.client; import cn.sticki.common.result.RestResult; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.multipart.MultipartFile; /** * @author 阿杆 */ @FeignClient(value = "resource-server", fallback = ResourceClientResolver.class) public interface ResourceClient { /** * 上传图片接口 * * @param file 图片 * @return 图片链接 */ @PostMapping(value = "/private/resource/image", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) RestResult<String> uploadBlogImage(@RequestPart MultipartFile file); }
ResourceClientResolver.java:
package cn.sticki.resource.client; import cn.sticki.common.result.RestResult; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import org.springframework.web.multipart.MultipartFile; /** * @author 阿杆 */ @Slf4j @Component public class ResourceClientResolver implements ResourceClient{ /** * 上传图片接口 * * @param file 图片 * @return 图片链接 */ @Override public RestResult<String> uploadBlogImage(MultipartFile file) { log.error("Resource 服务异常:uploadBlogImage 请求失败"); return new RestResult<>(503,"fail"); } }
上面两个文件所需要的主要依赖:
<!--feign客户端依赖--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> <version>2.2.10.RELEASE</version> </dependency>#Java##程序员#