springcloud(3):熔断器Hystrix

Feign Hystrix

因为熔断只是作用在服务调用这一端,因此我们根据上一篇的示例代码只需要改动spring-cloud-consumer项目相关代码就可以。因为,Feign中已经依赖了Hystrix所以在maven配置上不用做任何改动。

参考引用:http://www.ityouknow.com/springcloud/2017/05/16/springcloud-hystrix.html

实例

修改spring-cloud-consumer,达到熔断功能

(1)依赖

由于之前spring-cloud-consumer,已经用了Feign,而Feign又支持Hystrix,所以pom.xml不用修改

(2)配置

#用于远程调用的熔断
feign.hystrix.enabled=true

(3)创建回调类

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

@Component
public class HelloRemoteHystrix implements HelloRemote{

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

(4)添加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

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

猜你喜欢

转载自blog.csdn.net/qq_42683700/article/details/85258420