春季:春季缓存不起作用 [英] Spring : Spring-cache not working

查看:73
本文介绍了春季:春季缓存不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究Spring-MVC应用程序.在探查器经过后端之后,我注意到getCurrentlyAuthenticatedUser()是一个热点.由于这个原因,我想到了使用缓存.不幸的是,它不起作用.一旦用户登录,即使该用户已登录,我也将获得空用户.出了什么问题.当然,当我从XML删除@Cacheable批注和配置时,一切正常.任何帮助都很好.

I am working on a Spring-MVC application. After the profiler went through the backend, I noticed that getCurrentlyAuthenticatedUser() is an hotspot. For the reason I thought of using cache. Unfortunately it is not working. Once the user logs in, I am getting null user, even though the user is logged in. What is going wrong. Ofcourse when I remove the @Cacheable annotation and config from XML, everything works fine. Any help would be nice.

PersonServiceImpl:

PersonServiceImpl :

@Service
@Transactional
public class PersonServiceImpl implements PersonService {

  private final PersonDAO personDAO;

   @Autowired
    public PersonServiceImpl(PersonDAO personDAO) {
        this.personDAO = personDAO;
    }
 @Override
    @Cacheable(value = "person", condition = "#person == null")
    public Person getCurrentlyAuthenticatedUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            return null;
        } else {
            return personDAO.findPersonByUsername(authentication.getName());
        }
    }
}

用于使用缓存的配置:

  <cache:annotation-driven />

    <beans:bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
        <beans:property name="caches">
            <beans:set>
                <beans:bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean"
                        p:name="person"/>
           </beans:set>
        </beans:property>
    </beans:bean>

当我调用此方法时,无论是否登录,我都将返回null.你能帮忙的话,我会很高兴.谢谢.

when I call this method, even if logged in or not, I am getting null back. Any help would be nice. Thanks.

推荐答案

在下面的代码行中:-

@Cacheable(value = "person", condition = "#person == null")

尝试使用除非代替 condition

实际上,您已经提出了一个条件,即仅当人员为null时,缓存才起作用",这应类似于除非人员为null,否则缓存才起作用".编码愉快.

Actually you have put up an condition that "Caching will only work if the person is null", which should be like "Caching will work unless person is null". Happy coding.

这篇关于春季:春季缓存不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆