在上一篇中我们学习了如何使用feign调用远程接口,但当服务提供方宕机,或网络问题造成连接不可用,或服务提供方抛异常时,又该如何处理?
这篇我们来看如何使用断路器-hystrix。
首先我们启动eureka-feign(别忘了开启zookeeper),此时服务提供者eureka-client处于不可用的状态,
直接访问http://localhost:8082/test,会看到以下信息:
上面保存提示没有可用的回调方法,那么,给定一个回调方案不就可以解决了么。
这里就需要使用hystrix,是的,feign已经集成了hystrix的包,不需要额外引入依赖包。
1,改造TestClient.java,在@FeignClient中指定一个回调类,DefaultClient
package com.example;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@FeignClient(value="eureka-client",fallback=DefaultClient.class)
public interface TestClient {
@RequestMapping(value="/test",method=RequestMethod.GET)
String test();
}
2,新建DefaultClient.java,让其实现TestClient的test方法:
package com.example;
import org.springframework.stereotype.Component;
@Component
public class DefaultClient implements TestClient{
@Override
public String test() {
// TODO Auto-generated method stub
return "this is fallback method";
}
}
3,springcloud版本分为Brixton和Dalston两个,Brixton版本的feign是默认开启hystrix的,如果使用Dalston版本则需要在application.properties配置中添加:
feign.hystrix.enabled=true
下面重新启动eureka-feign,再次访问http://localhost:8082/test,就会调用本地的回调方法,得到响应结果: