Hystrix使用缓存例子

public class RestTemplateHystrixCommand extends HystrixCommand {

    private String key ;

    public RestTemplateHystrixCommand(String group,String key,String url,int threadSize) {
        super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(group))
                .andCommandKey(HystrixCommandKey.Factory.asKey(key))
                .andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey(url))
                .andCommandPropertiesDefaults(HystrixCommandProperties.Setter().withExecutionTimeoutEnabled(true)
                        .withExecutionTimeoutInMilliseconds(6000) //包括在等待中的时间
                        .withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.THREAD)
                        .withRequestCacheEnabled(true)
                )
                .andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter()
                        .withCoreSize(threadSize).withMaxQueueSize(5).withQueueSizeRejectionThreshold(3)
                ));
        this.key = key;
    }

    @Override
    protected String getCacheKey(){
        return this.key;
    }

    @Override
    protected Boolean run() throws Exception {
        System.out.println("执行了一个请求");
        Thread.sleep(5000);
        return true;
    }

    @Override
    protected Boolean getFallback() {
        log.info("请求失败");
        return false;
    }

    public static void main(String[] args) {
        Executor executor = Executors.newFixedThreadPool(30);

        HystrixRequestContext context = HystrixRequestContext.initializeContext();
        for(int i = 0; i<20 ;i++) {
            HystrixContextRunnable runnable =new HystrixContextRunnable(() -> {
                HystrixRequestContext context1 = HystrixRequestContext.getContextForCurrentThread();
                System.out.println("context is null " + (context1 == null));
                RestTemplateHystrixCommand restTemplateHystrixCommand =
                        new RestTemplateHystrixCommand("bws", "jx", "localhost", 5);
                Boolean result = (Boolean) restTemplateHystrixCommand.execute();
                System.out.println("任务:" + "执行结果" + result + "是否获取了缓存结果:" + restTemplateHystrixCommand.isResponseFromCache);
            });
            executor.execute(runnable);
        }

        try {
            Thread.sleep(20000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        context.shutdown();
    }
}

注意点 TimeoutInMilliseconds 是包括在队列中等待的时间

如果想使用缓存结果,

单线程情况:

初始化请求上下文

HystrixRequestContext context = HystrixRequestContext.initializeContext();

并重写getCacheKey方法

多线程情况:

子线程要使用

HystrixContextRunnable或HystrixContextCallable去创建,

并且父线程的 context 要在所有子线程执行结束后再调用 context.shutdown

Hystrix配置说明

  1. 统计滚动的时间窗口 default 10000 ten seconds
    withMetricsRollingStatisticalWindowInMilliseconds(10000)
  2. 滚动时间窗口 bucket 数量 default
    withMetricsRollingStatisticalWindowBuckets(10)
  3. 采样时间间隔 default 500
    withMetricsHealthSnapshotIntervalInMilliseconds(1)
  4. 熔断器在整个统计时间内是否开启的阀值,默认20。也就是10秒钟内至少请求20次,熔断器才发挥起作用
    withCircuitBreakerRequestVolumeThreshold(20)
  5. 默认:50。当出错率超过50%后熔断器启动.
    withCircuitBreakerErrorThresholdPercentage(30)
  6. 熔断器默认工作时间,默认:5秒.熔断器中断请求5秒后会关闭重试,如果请求仍然失败,继续打开熔断器5秒,如此循环
    withCircuitBreakerSleepWindowInMilliseconds(1000)
  7. 隔离策略
    withExecutionIsolationStrategy(ExecutionIsolationStrategy.SEMAPHORE)
  8. 信号量隔离时最大并发请求数
    withExecutionIsolationSemaphoreMaxConcurrentRequests(2)
  9. 命令组名,该命令属于哪一个组,可以帮助我们更好的组织命令。
    withGroupKey(HystrixCommandGroupKey.Factory.asKey(“HelloGroup”))
  10. 命令名称,每个CommandKey代表一个依赖抽象,相同的依赖要使用相同的CommandKey名称。依赖隔离的根本就是对相同CommandKey的依赖做隔离。
    andCommandKey(HystrixCommandKey.Factory.asKey(“Hello”)
  11. 所属线程池的名称,同样配置的命令会共享同一线程池,若不配置,会默认使用GroupKey作为线程池名称。
    andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey(“HelloThreadPool”))
  12. 命令属性,设置包括断路器的配置,隔离策略,降级设置,以及一些监控指标等。
  13. 线程池属性,配置包括线程池大小,排队队列的大小等。

hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=1000
超时时间,默认1000ms
execution.timeout.enabled
是否开启超时,默认true
execution.isolation.thread.interruptOnTimeout
当超时的时候是否中断(interrupt) HystrixCommand.run()执行

官方参考文档:

https://github.com/Netflix/Hystrix/wiki/Configuration#execution.isolation.strategy

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值