首页 文章资讯内容详情

springcloud(九)-Feign使用Hystrix

2026-06-01 2 花语

本文内容纲要:

-前言 -编码 -测试

前言

上一篇我们使用注解@HystrixCommond的fallbackMethod属性实现回退。然而,Feign是以接口形式工作的,它没有方法体,上一篇讲解的方式显然不适用于Feign。

那么Feign要如何整合Hystrix呢?不仅如此,如何实现Feign的回退。

在springcloud中,为Feign添加回退更加简单。事实上,springcloud默认已为Feign整合了Hystrix,要想为Feign打开Hystrix支持,只需要设置feign.hystrix.enabled=true即可。

编码

1.复制项目microservie-consumer-movie-feign,将ArtifactId修改为microservice-consumer-movie-feign-hystrix-fallback.

2.在application.yml中添加feign.hystrix.enabled:true,从而开启Feign的Hystrix支持。

server: port:8082 eureka: client: serviceUrl: defaultZone:http://localhost:8083/eureka/ instance: prefer-ip-address:true spring: application: name:microservice-consumer-movie feign: hystrix: enabled:true

3.将之前编写的Feign接口修改成如下内容:

@FeignClient(name="microservice-provider-user",fallback=FeignClientFallback.class) publicinterfaceUserFeignClient{ @RequestMapping(value="/{id}",method=RequestMethod.GET) publicUserfindById(@PathVariable("id")Longid); } @Component classFeignClientFallbackimplementsUserFeignClient{ publicUserfindById(Longid){ Useruser=newUser(); user.setId(-1L); user.setUsername("默认用户"); returnuser; } }

由代码可知,只需使用@FeignClient注解的fallback属性,就可为指定名称的Feign客户添加回退。

测试

启动microservice-discovery-eureka.

启动microservice-provider-user.

启动microservice-consumer-movie-feign-hystrix-fallback.

访问http://localhost:8082/user/1,可正常获得结果。

{"id":1,"username":"account1","name":"张三","age":20,"balance":98.23}

停止microservice-provider-user.

再次访问http://localhost:8082/user/1,可获得如下结果。说明当用户微服务不可用时,进入了回退的逻辑。

{"id":-1,"username":"默认用户","name":null,"age":null,"balance":null}

补充:在springcloudDalston之前的版本中,Feign默认开启Hystrix支持,无需设置feign.hystrix.enabled=true.从springcloudDalston版本开始,Feign的Hystrix支持默认关闭,需要手动设置开启。

由于代码过于简单,这里就不提交源码了。

本文内容总结:前言,编码,测试,

原文链接:https://www.cnblogs.com/fengyuduke/p/10792220.html