springcloud(四):熔断器Hystrix

因为熔断只是作用在服务调用这一端,因此我们根据上一篇的示例代码只需要改动spring-cloud-consumer项目相关代码就可以。

因为,Feign中已经依赖了Hystrix所以在maven配置上不用做任何改动。

1、配置文件

application.properties添加这一条:

feign.hystrix.enabled=true

2、创建回调类

创建HelloRemoteHystrix类继承与HelloRemote实现回调的方法

@Component
public class HelloRemoteHystrix implements HelloRemote{

    @Override
    public String hello(@RequestParam(value = "name") String name) {
        return "hello" +name+", this messge send failed ";
    }
}

3、添加fallback属性

HelloRemote类添加指定fallback类,在服务熔断的时候返回fallback类中的内容。

@FeignClient(name= "spring-cloud-producer",fallback = HelloRemoteHystrix.class)
public interface HelloRemote {

    @RequestMapping(value = "/hello")
    public String hello(@RequestParam(value = "name") String name);

}

测试

依次启动spring-cloud-eureka、spring-cloud-producer、spring-cloud-consumer三个项目。

浏览器中输入:http://localhost:9001/hello/neo

返回:hello neo,this is first messge

说明加入熔断相关信息后,不影响正常的访问。接下来我们手动停止spring-cloud-producer项目再次测试:

浏览器中输入:http://localhost:9001/hello/neo

返回:hello neo, this messge send failed

根据返回结果说明熔断成功。

 

原文地址:https://www.cnblogs.com/cnki/p/8976290.html