SpringCloud实战(四)——Hystrix线程隔离,请求缓存,请求合并

上篇文章已经简单的介绍了Hystrix的请求熔断和服务降级,本篇文章将介绍剩下的三个特性。

线程隔离:在Hystrix中, 主要通过线程池来实现资源隔离. 通常在使用的时候我们会根据调用的远程服务划分出多个线程池.比如说,一个服务调用两外两个服务,你如果调用两个服务都用一个线程池,那么如果一个服务卡在哪里,资源没被释放,后面的请求又来了,导致后面的请求都卡在哪里等待,导致你依赖的A服务把你卡在哪里,耗尽了资源,也导致了你另外一个B服务也不可用了。这时如果依赖隔离,某一个服务调用A B两个服务,如果这时我有100个线程可用,我给A服务分配50个,给B服务分配50个,这样就算A服务挂了,我的B服务依然可以用。

用法:使用注解的用法:加上groupKey和threadPoolKey,根据这两个参数进行线程池的划分

 @HystrixCommand(groupKey = "",threadPoolKey = "",fallbackMethod = "helloFallBack")

如果不用注解,就需要在Command的构造器中进行指定。

请求缓存:

为什么要有请求缓存?

做微服务的主要目的就是为了缓解高并发。如果调用一个服务调用的太频繁,缓存一下效果会更好,直接从缓存中取,而不是去服务中取,以减轻服务的压力。但是Hystrix的缓存比较鸡肋。

代码实操:

只需要在继承了HystrixCommand的类中重写getCacheKey()方法即可。

   @Override
    protected String getCacheKey() {
//这里返回的就先写死了
        return "hello";
    }

另外:需要在Controller中进行如下配置:

HystrixRequestContext.initializeContext();

否则报错如下:

java.lang.IllegalStateException: Request caching is not available. Maybe you need to initialize the HystrixRequestContext?
	at com.netflix.hystrix.HystrixRequestCache.get(HystrixRequestCache.java:104) ~[hystrix-core-1.5.12.jar:1.5.12]
	at com.netflix.hystrix.AbstractCommand$7.call(AbstractCommand.java:478) ~[hystrix-core-1.5.12.jar:1.5.12]

其实由这里我们就可以看出,这个请求是基于Request的,请求结束就销毁了,就代表着上面的初始化结束了,之前设置的缓存也就没有了,即每次请求都是不一样的缓存。

现在启动项目,访问localhost:9000/consumer

访问被分到其中一个服务上去了:

再刷新页面一次,发现请求并没有走缓存,依然去访问的服务。也就是说每次请求来了都会去进行初始化。

但是,如果代码如下的话,缓存就会生效:同样的commandGroupKey在一个业务里调用多次。

  @RequestMapping("/consumer")
    public String  helloConsumer() throws ExecutionException, InterruptedException {

        HystrixRequestContext.initializeContext();

        HelloServiceCommand command = new HelloServiceCommand("hello",restTemplate);

        command.execute();

        HelloServiceCommand command1 = new HelloServiceCommand("hello",restTemplate);

        command1.execute();

        return null;
    }

请求缓存就到这里,不做太多解释了。

请求合并:也是降低对服务的调用次数

代码实操:

首先自定义一个继承HystrixCollapser的类:

package com.cloud.demo.consumer;

import com.netflix.hystrix.HystrixCollapser;
import com.netflix.hystrix.HystrixCollapserKey;
import com.netflix.hystrix.HystrixCollapserProperties;
import com.netflix.hystrix.HystrixCommand;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 操作请求合并
 List:批量请求返回类型
 String:单个请求
 Long:请求类型
 */
public class ZnxBatchCommand extends HystrixCollapser<List<String>,String,Long>{


    //单个请求的id
    private Long id;

    private RestTemplate restTemplate;

    /**
      *@Author ZNX
      *@Date 2018/8/6 22:40
      *@Description:
     *   .withTimerDelayInMilliseconds(200):用来甄别合并请求的力度
      */
    public ZnxBatchCommand(RestTemplate restTemplate, Long id) {
        super(Setter.withCollapserKey(HystrixCollapserKey.Factory.asKey("laowangbatch"))
                .andCollapserPropertiesDefaults(HystrixCollapserProperties.Setter()
                        .withTimerDelayInMilliseconds(200)));
        this.id = id;
        this.restTemplate = restTemplate;
    }

    @Override
    public Long getRequestArgument() {
        return id;
    }

    /**
      *@Author ZNX
      *@Date 2018/8/6 22:42
      *@Description:进行请求的合并
      */
    @Override
    protected HystrixCommand<List<String>> createCommand(Collection<CollapsedRequest<String, Long>> collection) {
        List<Long> ids = new ArrayList<>(collection.size());
        ids.addAll(collection.stream().map(CollapsedRequest::getArgument).collect(Collectors.toList()));
        //发送请求
        ZnxCommand command = new ZnxCommand("laowang",restTemplate,ids);
        return command;
    }


    /**
      *@Author ZNX
      *@Date 2018/8/6 22:39
      *@Description:分发请求结果
      */
    @Override
    protected void mapResponseToRequests(List<String> results, Collection<CollapsedRequest<String, Long>> collection) {
        System.out.println("分配批量请求结果。。。");
        int count=0;
        for (CollapsedRequest<String, Long> collapsedRequest : collection) {
            String result = results.get(count++);
            collapsedRequest.setResponse(result);
        }

    }
}

接着用自定义一个类来继承Hystrix提供的HystrixCommand来进行服务请求:

package com.cloud.demo.consumer;

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.List;


/**
  *@Author ZNX
  *@Date 2018/8/6 22:34
  *@Description:这个command就是用来发送请求的
  */
public class ZnxCommand extends HystrixCommand<List<String>>{


    private RestTemplate restTemplate;

    private List<Long> ids;

    protected ZnxCommand(String commandGroupKey, RestTemplate restTemplate, List<Long> ids) {

        super(HystrixCommandGroupKey.Factory.asKey(commandGroupKey));
        this.restTemplate=restTemplate;
        this.ids=ids;
    }

    @Override
    protected List<String> run() throws Exception {
        System.out.println("发送请求。。。参数为:"+ids.toString()+Thread.currentThread().getName());
        String[] result = restTemplate.getForEntity("http://HELLO-SERVICE/znxs?ids={1}",String[].class, StringUtils.join(ids,",")).getBody();
        return Arrays.asList(result);
    }
}

Controller代码如下:

package com.cloud.demo.consumer;

import com.netflix.hystrix.HystrixRequestCache;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import rx.Observable;
import rx.Observer;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;


@RestController
public class ConsumerController {

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Autowired
    private HelloService helloService;


    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping("/consumer")
    public String  helloConsumer() throws ExecutionException, InterruptedException {

      HystrixRequestContext context =   HystrixRequestContext.initializeContext();

      /*
      创建三个请求
       */
      ZnxBatchCommand command = new ZnxBatchCommand(restTemplate,1L);
        ZnxBatchCommand command1 = new ZnxBatchCommand(restTemplate,1L);
        ZnxBatchCommand command2 = new ZnxBatchCommand(restTemplate,1L);

        /*
        用Future去异步获取
         */
        Future<String> future = command.queue();
        Future<String> future1 = command1.queue();

        String r = future.get();
        String r1 = future1.get();

        //睡2s,错过之前设置的200ms
        //前两条请求会被合并
        Thread.sleep(2000);

        Future<String> future2 = command2.queue();
        String r2 = future2.get();
        System.out.println(r);
        System.out.println(r1);
        System.out.println(r2);

        context.close();


        return null;
    }

}

给服务提供者增加一个方法用来模拟数据库数据:

package com.cloud.demo.hello;

import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 */
@RestController
public class HelloController {

    @RequestMapping("/hello")
    public  String hello () throws InterruptedException {
        System.out.println("访问来了。。");
        Thread.sleep(800);
        return "hello cloud";
    }

    @RequestMapping("/znxs")
    public List<String> znxs(String ids){
        List<String> list = new ArrayList<>();
        list.add("laowang1");
        list.add("laowang2");
        list.add("laowang3");
        return list;


    }

}

启动项目,访问localhost:9000/consumer

通过控制台可以看到,请求1和2被合并,请求3为单独的一个请求。

 

使用注解实现请求合并:

package com.cloud.demo.consumer;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCollapser;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Future;


@Service
public class ZnxService {

    @Autowired
    private RestTemplate restTemplate;

    @HystrixCollapser(batchMethod = "getZnx",collapserProperties = {@HystrixProperty(name = "timerDelayInMilliseconds",value = "200")})
    public Future<String> batchGetHjc(long id){
        return null;
    }

    @HystrixCommand
    public List<String> getLaoWang(List<Long> ids){
        System.out.println("发送请求的参数为:"+ids.toString()+Thread.currentThread().getName());
        String[] result = restTemplate.getForEntity("http://HELLO-SERVICE/znxs?ids={1}",String[].class, StringUtils.join(ids,",")).getBody();
        return Arrays.asList(result);
    }

}

 

常用的Hystrix属性:

1.Execution相关的属性的配置:

  • hystrix.command.default.execution.isolation.strategy 隔离策略,默认是Thread, 可选Thread|Semaphore

  • hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds 命令执行超时时间,默认1000ms

  • hystrix.command.default.execution.timeout.enabled 执行是否启用超时,默认启用true
  • hystrix.command.default.execution.isolation.thread.interruptOnTimeout 发生超时是是否中断,默认true
  • hystrix.command.default.execution.isolation.semaphore.maxConcurrentRequests 最大并发请求数,默认10,该参数当使用ExecutionIsolationStrategy.SEMAPHORE策略时才有效。如果达到最大并发请求数,请求会被拒绝。理论上选择semaphore size的原则和选择thread size一致,但选用semaphore时每次执行的单元要比较小且执行速度快(ms级别),否则的话应该用thread。
    semaphore应该占整个容器(tomcat)的线程池的一小部分。

2.Fallback相关的属性

这些参数可以应用于Hystrix的THREAD和SEMAPHORE策略

  • hystrix.command.default.fallback.isolation.semaphore.maxConcurrentRequests 如果并发数达到该设置值,请求会被拒绝和抛出异常并且fallback不会被调用。默认10
  • hystrix.command.default.fallback.enabled 当执行失败或者请求被拒绝,是否会尝试调用hystrixCommand.getFallback() 。默认true

3.Circuit Breaker相关的属性

  • hystrix.command.default.circuitBreaker.enabled 用来跟踪circuit的健康性,如果未达标则让request短路。默认true
  • hystrix.command.default.circuitBreaker.requestVolumeThreshold 一个rolling window内最小的请求数。如果设为20,那么当一个rolling window的时间内(比如说1个rolling window是10秒)收到19个请求,即使19个请求都失败,也不会触发circuit break。默认20
  • hystrix.command.default.circuitBreaker.sleepWindowInMilliseconds 触发短路的时间值,当该值设为5000时,则当触发circuit break后的5000毫秒内都会拒绝request,也就是5000毫秒后才会关闭circuit。默认5000
  • hystrix.command.default.circuitBreaker.errorThresholdPercentage错误比率阀值,如果错误率>=该值,circuit会被打开,并短路所有请求触发fallback。默认50
  • hystrix.command.default.circuitBreaker.forceOpen 强制打开熔断器,如果打开这个开关,那么拒绝所有request,默认false
  • hystrix.command.default.circuitBreaker.forceClosed 强制关闭熔断器 如果这个开关打开,circuit将一直关闭且忽略circuitBreaker.errorThresholdPercentage

4.Metrics相关参数

  • hystrix.command.default.metrics.rollingStats.timeInMilliseconds 设置统计的时间窗口值的,毫秒值,circuit break 的打开会根据1个rolling window的统计来计算。若rolling window被设为10000毫秒,则rolling window会被分成n个buckets,每个bucket包含success,failure,timeout,rejection的次数的统计信息。默认10000
  • hystrix.command.default.metrics.rollingStats.numBuckets 设置一个rolling window被划分的数量,若numBuckets=10,rolling window=10000,那么一个bucket的时间即1秒。必须符合rolling window % numberBuckets == 0。默认10
  • hystrix.command.default.metrics.rollingPercentile.enabled 执行时是否enable指标的计算和跟踪,默认true
  • hystrix.command.default.metrics.rollingPercentile.timeInMilliseconds 设置rolling percentile window的时间,默认60000
  • hystrix.command.default.metrics.rollingPercentile.numBuckets 设置rolling percentile window的numberBuckets。逻辑同上。默认6
  • hystrix.command.default.metrics.rollingPercentile.bucketSize 如果bucket size=100,window=10s,若这10s里有500次执行,只有最后100次执行会被统计到bucket里去。增加该值会增加内存开销以及排序的开销。默认100
  • hystrix.command.default.metrics.healthSnapshot.intervalInMilliseconds 记录health 快照(用来统计成功和错误绿)的间隔,默认500ms

5.Request Context 相关参数

hystrix.command.default.requestCache.enabled 默认true,需要重载getCacheKey(),返回null时不缓存
hystrix.command.default.requestLog.enabled 记录日志到HystrixRequestLog,默认true

6.Collapser Properties 相关参数

hystrix.collapser.default.maxRequestsInBatch 单次批处理的最大请求数,达到该数量触发批处理,默认Integer.MAX_VALUE
hystrix.collapser.default.timerDelayInMilliseconds 触发批处理的延迟,也可以为创建批处理的时间+该值,默认10
hystrix.collapser.default.requestCache.enabled 是否对HystrixCollapser.execute() and HystrixCollapser.queue()的cache,默认true

7.ThreadPool 相关参数

线程数默认值10适用于大部分情况(有时可以设置得更小),如果需要设置得更大,那有个基本得公式可以follow:
requests per second at peak when healthy × 99th percentile latency in seconds + some breathing room
每秒最大支撑的请求数 (99%平均响应时间 + 缓存值)
比如:每秒能处理1000个请求,99%的请求响应时间是60ms,那么公式是:
1000 (0.060+0.012)

基本得原则时保持线程池尽可能小,他主要是为了释放压力,防止资源被阻塞。
当一切都是正常的时候,线程池一般仅会有1到2个线程激活来提供服务

    • hystrix.threadpool.default.coreSize 并发执行的最大线程数,默认10
    • hystrix.threadpool.default.maxQueueSize BlockingQueue的最大队列数,当设为-1,会使用SynchronousQueue,值为正时使用LinkedBlcokingQueue。该设置只会在初始化时有效,之后不能修改threadpool的queue size,除非reinitialising thread executor。默认-1。
    • hystrix.threadpool.default.queueSizeRejectionThreshold 即使maxQueueSize没有达到,达到queueSizeRejectionThreshold该值后,请求也会被拒绝。因为maxQueueSize不能被动态修改,这个参数将允许我们动态设置该值。if maxQueueSize == -1,该字段将不起作用
    • hystrix.threadpool.default.keepAliveTimeMinutes 如果corePoolSize和maxPoolSize设成一样(默认实现)该设置无效。如果通过plugin(https://github.com/Netflix/Hystrix/wiki/Plugins)使用自定义实现,该设置才有用,默认1.
    • hystrix.threadpool.default.metrics.rollingStats.timeInMilliseconds 线程池统计指标的时间,默认10000
    • hystrix.threadpool.default.metrics.rollingStats.numBuckets 将rolling window划分为n个buckets,默认10
  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值