阿里云-云小站(无限量代金券发放中)
【腾讯云】云服务器、云数据库、COS、CDN、短信等热卖云产品特惠抢购

在Feign中使用Hystrix实现服务调用容错

106次阅读
没有评论

共计 1510 个字符,预计需要花费 4 分钟才能阅读完成。

1、在 Feign 中用 Hystrix 实现服务调用容错

1.1、添加依赖和配置,并启用支持

1.1.1、添加依赖

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>

1.1.2、添加配置

spring.application.name=hystrix
server.port=50007
eureka.client.fetch-registry=true
eureka.client.register-with-eureka=false
eureka.client.service-url.defaultZone=http://eureka01:50001/eureka/,http://eureka02:50002//eureka/
#开启支持
feign.hystrix.enabled=true

1.1.3、添加对 Feign 的支持

@EnableFeignClients // 开启 Feign 支持 @SpringBootApplication public class HystrixSpringcloudApplication {public static void main(String[] args) {SpringApplication.run(HystrixSpringcloudApplication.class, args); } }

1.2、添加 Feign 接口

@FeignClient(name = "provider") public interface FeignClients {@GetMapping("/hello") public String hello(); }

1.3、添加 Controller

@RestController public class HelloController {@Autowired FeignClients feignClients; @GetMapping("/hello") public String index(){return feignClients.hello();} }

1.4、实现回调类

@Component public class HelloHstrix implements FeignClients {@Override public String hello() {return "出现错误!"; } }

1.5、添加 fallback 属性

@FeignClient(name = "provider",fallback = HelloHstrix.class) public interface FeignClients {@GetMapping("/hello") public String hello(); }

1.6、测试 fallbakc 状态

只开启 ” 服务中心 ”,访问 http://localhost:50007/hello,会提示错误。当把 ” 服务提供者 ” 也开启则会返回正确的数据。

正文完
星哥说事-微信公众号
post-qrcode
 
星锅
版权声明:本站原创文章,由 星锅 2022-06-06发表,共计1510字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
【腾讯云】推广者专属福利,新客户无门槛领取总价值高达2860元代金券,每种代金券限量500张,先到先得。
阿里云-最新活动爆款每日限量供应
评论(没有评论)
验证码
【腾讯云】云服务器、云数据库、COS、CDN、短信等云产品特惠热卖中