如何从异步线程访问会话

时间:2017-07-28 11:35:25

标签: java spring multithreading session asynchronous

我需要在异步作业中使用一些会话范围数据。该作业使用Spring @Async注释运行。 为了实现这一目标,首先在请求线程中记住请求属性:

currentAttributes = RequestContextHolder.getRequestAttributes();

然后,在运行异步作业的线程中,将恢复请求属性:

RequestContextHolder.setRequestAttributes(currentAttributes);

几乎一切正常 - 会话bean可用。但是,我无法访问HttpSession对象 - 检查会话是否仍然有效。 在会话范围的bean中:

@Autowired
transient private HttpSession session;
//...
private boolean isSessionInvalid() {
    try {
        session.getCreationTime();
        return false;
    } catch (IllegalStateException e) {
        return true;
    }
}

即使会话仍然有效,电话session.getCreationTime()也会引发IllegalStateException

java.lang.IllegalStateException: The request object has been recycled and is no longer associated with this facade
    at org.apache.catalina.connector.RequestFacade.getSession(RequestFacade.java:904)
    at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:240)
    at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:240)
    at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:240)
    at org.springframework.web.context.support.WebApplicationContextUtils$SessionObjectFactory.getObject(WebApplicationContextUtils.java:366)
    at org.springframework.web.context.support.WebApplicationContextUtils$SessionObjectFactory.getObject(WebApplicationContextUtils.java:361)
    at org.springframework.beans.factory.support.AutowireUtils$ObjectFactoryDelegatingInvocationHandler.invoke(AutowireUtils.java:307)

如何通过异步作业提供会话?或者,是否有其他方法来检查会话是否仍然有效?

0 个答案:

没有答案