折叠方法上的@HystrixCollapser空指针异常

时间:2018-03-11 18:34:00

标签: spring spring-cloud-netflix hystrix

嗨我有简单折叠方法的问题: 我的控制器:

@GetMapping(path = "/collapsed/{id}")
public Car getFromServiceCollapsed(@PathVariable Integer id) throws Exception{
    Car result =  carService.getCollapsed(id).get();
    return result;
}

和服务:

@HystrixCollapser(batchMethod = "getCollapsedCars",
        collapserProperties = {
            @HystrixProperty(name = "timerDelayInMilliseconds", value = "100"),
            @HystrixProperty(name = "requestCache.enabled", value = "true")
        },
        collapserKey = "getCollapsed")
public Future<Car> getCollapsed(Integer id){
    return null;
}

@HystrixCommand(groupKey = "getCircuitService",
        threadPoolKey = "getCircuitService",
        threadPoolProperties = {
                @HystrixProperty(name = "coreSize", value = "10"),
                @HystrixProperty(name = "maximumSize", value = "14"),
                @HystrixProperty(name = "maxQueueSize", value = "20")
        },
        commandProperties = {
                @HystrixProperty(name = "execution.isolation.strategy", value = "THREAD"),
                @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "2000"),
                @HystrixProperty(name = "execution.timeout.enabled", value = "true")
        },
        fallbackMethod = "getDefault")
private List<Car> getCollapsedCars(List<Integer> ids){
    LOGGER.debug("Collapse for {}", ids.size());
    return ids.stream().map(this::getCar).collect(Collectors.toList());
}

调用控制器时它会抛出异常:

java.lang.NullPointerException: null
at com.netflix.hystrix.HystrixCollapser$3.call(HystrixCollapser.java:398) ~[hystrix-core-1.5.12.jar:1.5.12]
at com.netflix.hystrix.HystrixCollapser$3.call(HystrixCollapser.java:382) ~[hystrix-core-1.5.12.jar:1.5.12]

但是当我在每个控制器调用上使用初始化HystrixRequestContext修改控制器时它开始工作但不太好 - 服务方法getCollapsedCars总是记录:&#34;折叠为1&#34; - 但是我一个接一个地发送20个RQ,只有1毫秒的时间。

修改后的控制器:

@GetMapping(path = "/collapsed/{id}")
public Car getFromServiceCollapsed(@PathVariable Integer id) throws Exception{
    HystrixRequestContext context = HystrixRequestContext.initializeContext();
    Car result =  carService.getCollapsed(id).get();
    context.shutdown();
    return result;
}

如何使折叠命令正常工作?

1 个答案:

答案 0 :(得分:0)

我面临着同样的问题。请求未按批次分组。 但问题是HystrixRequestContext,因为这是您的请求的本地。

请删除本地HystrixRequestContext创建并将其作为范围添加到collapser。

@HystrixCollapser(scope = com.netflix.hystrix.HystrixCollapser.Scope.GLOBAL,batchMethod = ..............)

并且瞧!!!“