继之前的项目继续扩展,整合hystrix和feign这两个框架。
1、修改服务器调用者的application.yml,增加如下代码
# 打开feign对hystrix的支持
feign:
hystrix:
enabled: true
# 配置hystrix
hystrix:
threadpool:
default:
coreSize: 10 #线程池核心线程数
command:
#IService#hello(): 设置某一个接口 default: 设置全部接口
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 1000 #超时时间
circuitBreaker:
requestVolumeThreshold: 3 #当在配置时间窗口内达到此数量后,进行短路。默认20个
sleepWindowInMilliseconds: 5 #短路多久以后开始尝试是否恢复,默认5s
errorThresholdPercentage: 50% #出错百分比阈值,当达到此阈值后,开始短路。默认50%
2、修改之前的Iservice.java接口,增加fallback = IserviceFallback.class参数,这是接口的错误回调类
@FeignClient(value = "eureka-service", fallback = IServiceFallback.class)
public interface IService {
@GetMapping("/hello")
String hello();
}
3、创建错误回调类IserviceFallback.java
@Component
public class IServiceFallback implements IService {
@Override
public String hello() {
return "fallback_hello";
}
}
4、controller中编写一个测试接口,Thread.sleep(1000),为了测试错误回退逻辑
@GetMapping(value = "/hello", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public String hello() throws InterruptedException {
Thread.sleep(1000);
String hello = iService.hello();
return "hello : " + hello;
}
5、如果有统一的业务处理方法,可以扩展hystrix的拦截器
在启动类上增加@ServletComponentScan注解来扫描拦截器
创建MyFilter.java
@WebFilter(urlPatterns = "/*", filterName = "hystrixFilter")
@Component
public class Myfilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain filterChain) throws IOException, ServletException {
System.out.println("===================MyFilter====================");
// 初始化 hystrix 请求上下文
HystrixRequestContext hystrixRequestContext = HystrixRequestContext.initializeContext();
/* 业务逻辑 */
try{
filterChain.doFilter(servletRequest, servletResponse);
}catch (Exception e){
e.printStackTrace();
}finally {
hystrixRequestContext.shutdown();
}
}
@Override
public void destroy() {}
}
6、断路器的测试,修改Controller的hello()接口
@GetMapping(value = "/hello", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public String hello() throws InterruptedException {
String hello = iService.hello();
// 获取断路器对接口的开启状态,默认false
HystrixCircuitBreaker hystrixCircuitBreaker = HystrixCircuitBreaker.Factory
.getInstance(HystrixCommandKey.Factory.asKey("IService#hello()"));
System.out.println(hystrixCircuitBreaker.isOpen() + "");
return "hello : " + hello;
}
编写一个执行函数,同时启动20个线程来访问hello接口
/**
* 测试断路器
*
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
RestTemplate restTemplate = new RestTemplate();
for (int i = 0; i < 20; i++) {
Thread thread = new Thread() {
@Override
public void run() {
try {
String templateUrl = "http://127.0.0.1:8666/sayHello";
String result = restTemplate.getForObject(templateUrl, String.class);
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
}
};
thread.start();
}
Thread.sleep(20000);
}