我是靠谱客的博主 动听金针菇,这篇文章主要介绍使用Hystrix缓存时报没初始化HystrixRequestContext的错误,现在分享给大家,希望可以做个参考。

使用Hystrix缓存时报没初始化HystrixRequestContext的错误:

java.lang.IllegalStateException: Request caching is not available. Maybe you need to initialize the HystrixRequestContext?
at com.netflix.hystrix.HystrixRequestCache.get(HystrixRequestCache.java:104)
at com.netflix.hystrix.AbstractCommand$7.call(AbstractCommand.java:478)
at com.netflix.hystrix.AbstractCommand$7.call(AbstractCommand.java:454)
at rx.internal.operators.OnSubscribeDefer.call(OnSubscribeDefer.java:46)
at rx.internal.operators.OnSubscribeDefer.call(OnSubscribeDefer.java:35)
at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48)

解决方法:
1.在每个用到请求缓存的Controller方法里加上如下代码:

//初始化Hystrix请求上下文
HystrixRequestContext context = HystrixRequestContext.initializeContext();
//省略中间代码上下文环境用完需要关闭
context.close();

2.使用Filter全局过滤

@WebFilter(filterName = "hystrixRequestContextServletFilter",urlPatterns = "/*",asyncSupported = true)
public class HystrixRequestContextServletFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//初始化Hystrix请求上下文
HystrixRequestContext context = HystrixRequestContext.initializeContext();
try {
//请求正常通过
filterChain.doFilter(servletRequest, servletResponse);
} finally {
//关闭Hystrix请求上下文
context.shutdown();
}
}
@Override
public void destroy() {
}
}

并在启动类上加上@ServletComponentScan注解。

最后

以上就是动听金针菇最近收集整理的关于使用Hystrix缓存时报没初始化HystrixRequestContext的错误的全部内容,更多相关使用Hystrix缓存时报没初始化HystrixRequestContext内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(114)

评论列表共有 0 条评论

立即
投稿
返回
顶部