版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_30038111/article/details/85015890
<dependency>
<groupId>com.netflix.hystrix</groupId>
<artifactId>hystrix-core</artifactId>
<version>1.5.12</version>
</dependency>
package com.roncoo.eshop.cache.ha.hystrix.command;
import org.springframework.boot.context.embedded.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixCommandProperties;
import com.netflix.hystrix.HystrixRequestCache;
import com.netflix.hystrix.HystrixThreadPoolKey;
import com.netflix.hystrix.HystrixThreadPoolProperties;
import com.netflix.hystrix.HystrixCommandProperties.ExecutionIsolationStrategy;
import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategyDefault;
import com.roncoo.eshop.cache.ha.filter.HystrixRequestContextFilter;
/**
* @ClassName: HystrixCommandDemo
* @date 2018年12月15日 下午2:17:51
*/
public class HystrixCommandDemo extends HystrixCommand<String> {
private String key;
private static final HystrixCommandKey COMMAND_KEY = HystrixCommandKey.Factory.asKey("key");
public HystrixCommandDemo(String key) {
super(Setter
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("groupKeyName"))
.andCommandKey(COMMAND_KEY)
.andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey("threadPoolKey"))
.andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter().withCoreSize(10).withQueueSizeRejectionThreshold(10))
.andCommandPropertiesDefaults(
HystrixCommandProperties.Setter().withFallbackIsolationSemaphoreMaxConcurrentRequests(20).withExecutionTimeoutEnabled(true)
.withExecutionTimeoutInMilliseconds(1000).withExecutionIsolationStrategy(ExecutionIsolationStrategy.SEMAPHORE)
.withExecutionIsolationSemaphoreMaxConcurrentRequests(15).withCircuitBreakerEnabled(true)
.withCircuitBreakerRequestVolumeThreshold(20).withCircuitBreakerRequestVolumeThreshold(50)
.withCircuitBreakerSleepWindowInMilliseconds(5000).withCircuitBreakerErrorThresholdPercentage(50)
.withCircuitBreakerForceOpen(false).withCircuitBreakerForceClosed(false)));
// 组名,统一管理命令,比如报告、警报、仪表盘和。默认情况下,HystrixCommandGroupKey的名字即为线程池的名字,除非自定义线程池
Setter setter = Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("groupKeyName"));
// 命令的名称
setter.andCommandKey(COMMAND_KEY);
// 不指定线程池时,hystrix会默认以HystrixCommandGroupKey创建一个,一个HystrixCommand与一个HystrixThreadPoolKey相关联
setter.andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey("threadPoolKey"));
// 线程池核心线程数及队列容量
setter.andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter().withCoreSize(10).withQueueSizeRejectionThreshold(10));
// fallback降级信号量数
setter.andCommandPropertiesDefaults(HystrixCommandProperties.Setter().withFallbackIsolationSemaphoreMaxConcurrentRequests(20));
// 是否开启command超时,默认为true
// 设置command执行超时时间,如果超时,将调用fallback降级
setter.andCommandPropertiesDefaults(HystrixCommandProperties.Setter().withExecutionTimeoutEnabled(true).withExecutionTimeoutInMilliseconds(1000));
// 信号量资源隔离与限流
setter.andCommandPropertiesDefaults(HystrixCommandProperties.Setter().withExecutionIsolationStrategy(ExecutionIsolationStrategy.SEMAPHORE)
.withExecutionIsolationSemaphoreMaxConcurrentRequests(15));
// 是否允许断路器工作,包括跟踪服务调用的健康状况、异常请求过多是否允许开启断路器,默认为true
// 最少要有多少个请求才触发断路器,默认值为20;
// 短路之后,在多少毫秒之内对请求直接reject,然后在这段时间之后,引导断路器half-open,尝试自动恢复,默认值5000毫秒;
// 设置异常请求量百分比,当异常请求达到这个百分比,开启断路器,默认50%;
// 是否手动打开断路器,默认false;
// 是否手动关闭断路器,默认false;
setter.andCommandPropertiesDefaults(HystrixCommandProperties.Setter().withCircuitBreakerEnabled(true).withCircuitBreakerRequestVolumeThreshold(20)
.withCircuitBreakerSleepWindowInMilliseconds(5000).withCircuitBreakerErrorThresholdPercentage(50).withCircuitBreakerForceOpen(false)
.withCircuitBreakerForceClosed(false));
this.key = key;
}
@Override
protected String run() throws Exception {
return null;
}
/**
* request cache,对每一次请求,都初始化一个hystrix的请求上下文,java web通常用filter来实现
* public class HystrixRequestContextFilter implements Filter {
public void init(FilterConfig config) throws ServletException {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HystrixRequestContext context = HystrixRequestContext.initializeContext();
try {
chain.doFilter(request, response);
} catch (Exception e) {
e.printStackTrace();
} finally {
context.shutdown();
}
}
public void destroy() {
}
}
@Bean
public FilterRegistrationBean filterRegistrationBean() {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(
new HystrixRequestContextFilter());
filterRegistrationBean.addUrlPatterns("/*");
return filterRegistrationBean;
}
* @Title: getCacheKey
* @see com.netflix.hystrix.AbstractCommand#getCacheKey()
* @return
*/
@Override
protected String getCacheKey() {
return "key:" + key;
}
/**
* 手动删除hystrix的request cache
* @Title: flushCacheKey
* @param key
*/
public static void flushCacheKey(String key) {
HystrixRequestCache.getInstance(COMMAND_KEY, HystrixConcurrencyStrategyDefault.getInstance()).clear(key);
}
/**
* 通过信号量控制并发请求的降级,默认是10,如果超过了10,则会reject
* 可以通过.andCommandPropertiesDefaults(HystrixCommandProperties.Setter().withFallbackIsolationSemaphoreMaxConcurrentRequests(20))配置
* @Title: getFallback
* @see com.netflix.hystrix.HystrixCommand#getFallback()
* @return
*/
@Override
protected String getFallback() {
return null;
}
}