为什么HystrixRequestContext没有初始化?

时间:2018-03-18 09:38:03

标签: spring-boot spring-cloud spring-cloud-netflix

我尝试编写HystrixCollapser演示,但总是失败并记录:

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]
at rx.internal.operators.OnSubscribeDefer.call(OnSubscribeDefer.java:46) ~[rxjava-1.2.0.jar:1.2.0]
at rx.internal.operators.OnSubscribeDefer.call(OnSubscribeDefer.java:35) ~[rxjava-1.2.0.jar:1.2.0]
at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48) ~[rxjava-1.2.0.jar:1.2.0]

我正在使用 Edgware.SR2 ,我的配置:

@EnableCircuitBreaker
@EnableEurekaClient
@SpringBootApplication
public class EurekaClient1Application {

    @LoadBalanced
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

    public static void main(String[] args) {
        SpringApplication.run(EurekaClient1Application.class, args);
    }
}

和HystrixCollapser方法:

@HystrixCollapser(batchMethod = "getAll")
public Integer get(Integer index) {
    logger.info("invoke getOne !!!!!!!!!!!!");
    return restTemplate.getForObject("http://eureka-client-2/getOne/{1}",Integer.class,index);
}

@HystrixCommand(fallbackMethod = "getAllError")
public List<Integer> getAll(List<Integer> indices) {
    logger.info("invoke multi !!!!!!!!!!!!!!!");
    final String ids = indices.toString().replaceAll("\\[|\\]", "");
    return restTemplate.getForObject("http://eureka-client-2/getMulti?ids={1}", List.class, ids);
}

private List<Integer> getAllError(List<Integer> indices) {
    return Collections.emptyList();
}

我发现这里返回null值:

public class HystrixLifecycleForwardingRequestVariable<T> extends HystrixRequestVariableDefault<T> {
.....

    @Override
    public T get() {
        if (!HystrixRequestContext.isCurrentThreadInitialized()) {
            return null;
        }
        return super.get();
    }

所以我在HystrixCollapser方法之前调用HystrixRequestContext.initializeContext();,一切正常。但我认为它应该是autoconfig。什么遗失?

0 个答案:

没有答案