上一篇博客讲解了Ribbon使用Hystrix,本篇博客讲解下Feign使用Hystrix。
一、准备
将服务消费者(Ribbon)使用博客中的Consumer-Ribbon工程,复制一份,命名为Consumer-Ribbon-Hystrix。
二、工程修改
Feign是自带断路器的,在D版本的Spring Cloud中,它没有默认打开。需要在配置文件中配置打开它,在配置文件加以下代码,feign.hystrix.enabled=true。
spring.application.name=consumer-feign-hystrix
server.port=10009
eureka.client.serviceUrl.defaultZone=http://localhost:10001/eureka/
feign.hystrix.enabled=true
工程gradle依赖为
dependencies {
compile('org.springframework.boot:spring-boot-starter-web')
compile('org.springframework.cloud:spring-cloud-starter-feign:1.4.4.RELEASE')
compile('org.springframework.cloud:spring-cloud-starter-eureka:1.4.4.RELEASE')
compile('org.springframework.cloud:spring-cloud-starter-ribbon:1.4.4.RELEASE')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
新建ConsumerServiceHystric熔断器处理类,实现ConsumerService接口
import org.springframework.stereotype.Component;
/**
* Created by wzj on 2018/5/21.
*/
@Component
public class ConsumerServiceHystric implements ConsumerService
{
@Override
public String client()
{
return "Consumer feign [client] error";
}
}
修改ConsumerService接口类,添加fallback异常处理回调。
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* Created by wzj on 2018/5/20.
*/
@FeignClient(value = "service-producer",fallback = ConsumerServiceHystric.class)
public interface ConsumerService
{
@RequestMapping(value = "/client",method = RequestMethod.GET)
String client();
}
ConsumerFeignApplication启动类和ConsumerController不变。
三、测试
启动Eureka-Server、Service-Producer-A和该工程,浏览器访问http://127.0.0.1:10009/consumer,服务可以正常调用。

关闭Service-Producer-A服务,再次访问,服务调用出现问题,自动访问fallback函数。

本文介绍了如何在Spring Cloud项目中使用Feign结合Hystrix实现断路器功能。通过复制并修改Consumer-Ribbon工程,配置启用Feign的Hystrix断路器,创建熔断器处理类,并设置异常回调。当服务提供者不可用时,断路器自动触发回退策略。
:Feign熔断器使用(Hystrix)&spm=1001.2101.3001.5002&articleId=80399102&d=1&t=3&u=5e18d988d56b49dfa233b904d1f113c0)
610

被折叠的 条评论
为什么被折叠?



