简体   繁体   English

春季:春季缓存不起作用

[英]Spring : Spring-cache not working

I am working on a Spring-MVC application. 我正在开发Spring-MVC应用程序。 After the profiler went through the backend, I noticed that getCurrentlyAuthenticatedUser() is an hotspot. 在探查器经过后端之后,我注意到getCurrentlyAuthenticatedUser()是一个热点。 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. 当然,当我从XML删除@Cacheable批注和配置时,一切正常。 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());
        }
    }
}

config for using cache : 使用缓存的配置:

  <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>

when I call this method, even if logged in or not, I am getting null back. 当我调用此方法时,无论是否登录,我都将返回null。 Any help would be nice. 你能帮忙的话,我会很高兴。 Thanks. 谢谢。

In the below code line:- 在下面的代码行中:

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

Try to use unless in place of condition unless condition unless请尝试使用

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". 实际上,您已经提出了一个条件,即“仅当人员为null时才可以使用缓存”,这就像“除非人员为null时才可以使用缓存”。 Happy coding. 快乐的编码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM