Spring Cloud基础教程(六):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函数。


猜你喜欢

转载自blog.csdn.net/u010889616/article/details/80399102