Spring Cloud基础教程(六):Feign熔断器使用(Hystrix)

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

上一篇博客讲解了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函数。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

dmfrm

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值