zhihu-spider之Hystrix——zhihu-spider开源项目使用技术详解(其七)
1.Feign简介
Netflix的创造了一个调用的库Hystrix实现了断路器图案。在微服务架构中,通常有多层服务调用。
较低级别的服务中的服务故障可能导致用户级联故障。当对特定服务的呼叫达到一定阈值时(Hystrix中的默认值为5秒内的20次故障),电路打开,不进行通话。在错误和开路的情况下,开发人员可以提供后备。
开放式电路会停止级联故障,并允许不必要的或失败的服务时间来愈合。回退可以是另一个Hystrix保护的调用,静态数据或一个正常的空值。回退可能被链接,所以第一个回退使得一些其他业务电话又回到静态数据。
官方地址:http://cloud.spring.io/spring-cloud-static/Dalston.SR2/#_circuit_breaker_hystrix_clients
中文官方地址:https://springcloud.cc/spring-cloud-dalston.html#_circuit_breaker_hystrix_clients
2.配置Hystrix
//gradle依赖如下
compile "org.springframework.cloud:spring-cloud-starter-hystrix:1.2.3.RELEASE"
//maven依赖如下
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
<version>1.2.3.RELEASE</version>
</dependency>
Java Config配置
#HystrixConfiguration.java做如下配置
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.netflix.hystrix.contrib.javanica.aop.aspectj.HystrixCommandAspect;
/**
*
*
* @author sunzc
*
* 2017年6月10日 上午9:41:19
*/
@Configuration
public class HystrixConfiguration {
/**
* hystrix aop配置
*
* @return
*/
@Bean
public HystrixCommandAspect hystrixAspect() {
return new HystrixCommandAspect();
}
}
3.Hystrix使用
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.wei.you.zhihu.spider.service.client.ZhihuRecommendationClient.ZhihuHystrixClientFallback;
/**
* 知乎FeignClient的客户端
*
* @author sunzc
*
* 2017年6月7日 下午8:04:29
*/
@FeignClient(name = "zhihu", url = "https://www.zhihu.com", fallback = ZhihuHystrixClientFallback.class)
public interface ZhihuRecommendationClient {
@RequestMapping(method = RequestMethod.GET, value = "/explore/recommendations", consumes = { "application/json" })
String getRecommendation();
/**
* 这边采取了和Spring
* Cloud官方文档相同的做法,将fallback类作为内部类放入Feign的接口中,当然也可以单独写一个fallback类。
*
* @author sunzc
*/
@Component
static class ZhihuHystrixClientFallback implements ZhihuRecommendationClient {
private static final Logger loggger = LoggerFactory.getLogger(ZhihuHystrixClientFallback.class);
private final static String DEFAULT_STR = "<html>error</html>";
/**
* hystrix fallback方法
*
* @return 默认的返回值
*/
@Override
public String getRecommendation() {
loggger.error("异常发生,进入fallback方法");
return DEFAULT_STR;
}
}
}
4.项目的开源地址