Async和EhCache不适用于登录的第二个用户

时间:2018-04-09 14:55:47

标签: java spring-mvc asynchronous ehcache future

我正在尝试使用@cacheable实现@async,如下所示..

@RequestMapping(value="ehcacheExample")
public ModelAndView loadehcacheExamplePage(HttpServletRequest request, HttpSession session, ModelAndView modelAndView) {

    cacheHelper.getDataUsingAsyncAndStoreInEhcache(userInfo, session);

    //diffetent execution
    ...

    return modelAndView;
}

并且

@Cacheable(value="cacheKey")
public Future<String> getDataUsingAsyncAndStoreInEhcache(UserLoginSessionInfo userInfo,
        HttpSession session) {
    return ehcacheExampleDelegate.getDataUsingAsyncAndStoreInEhcache(userInfo,session);
}
  

@Async
public Future<String> getDataUsingAsyncAndStoreInEhcache(UserLoginSessionInfo userInfo, 
    HttpSession session) {

    //Async execution
    return new AsyncResult<String>(jsonInString);
}

根据我的理解,这个'getDataUsingAsyncAndStoreInEhcache'方法产生独立于调用方法的结果,将其保存在ehcache实现中。所以,下次我调用ajax方法从未来获取数据时,我正在实现以下实现 -

@RequestMapping(value="getCachedData")
    public @ResponseBody String getCachedData(HttpSession session) {
        UserLoginSessionInfo userInfo = HttpRequestSessionUtils.getLoggedinUserSessionInfo(session);

        Future<String> cachedData = cacheHelper.getDataUsingAsyncAndStoreInEhcache(userInfo, session);
        …
        return dataFromFuture; 

    }

现在我的期望是,如果任何其他用户在第一个用户之后登录,则cacheHelper.getDataUsingAsyncAndStoreInEhcache(userInfo, session)不应该执行整个方法。相反,它应该从Ehcache内存中检索数据。

但它没有发生。我可以确保缓存正在工作,因为在同一会话中,如果用户多次调用getCachedData ajax调用,它只从缓存返回数据。但问题出现在cacheHelper.getDataUsingAsyncAndStoreInEhcache(userInfo, session)实现中(在@RequestMapping(value="ehcacheExample")方法中提到)。

请你帮助我理解为什么这个方法整个执行,每次用户调用loadehcacheExamplePage方法而不是在第二个用户登录时从缓存中检索它?

1 个答案:

答案 0 :(得分:0)

我在这里看到了不同的可能问题。首先,Spring中的缓存和异步之间有bug。但是,我不认为它与您相关,因为您的CacheHelperCacheHelperDelegate不是同一个对象。

现在,它将被缓存的Future。不是它返回的值。这很奇怪。但它应该仍然有效。

最后,Spring默认使用参数作为缓存键。在您的情况下UserLoginSessionInfo userInfo, HttpSession session。这些是高度用户特定的。因此,对于两个不同的用户,将调用该方法是正常的。如果这不是您想要的,您可能不需要传递这些参数。你也可以告诉Spring使用什么作为@Cacheable(key=...)的密钥。