【发布时间】:2015-10-28 04:28:47
【问题描述】:
我正在开发一个使用 Spring-Security 进行身份验证的 Spring-MVC 应用程序。由于过度使用获取当前经过身份验证的用户机制,Profiler 将其显示为“分配热点”,单个用户消耗了近 9.5kb 的内存。有没有办法优化这个基础设施。
PersonServiceImpl :
@Override
public Person getCurrentlyAuthenticatedUser() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null) {
return null;
} else {
return personDAO.findPersonByUsername(authentication.getName());
}
}
如果我总能以某种方式将用户推送到某个缓存中,从第一次检索后检索它的位置,至少应该会提高性能,但我不知道该怎么做。欢迎任何建议。谢谢。
【问题讨论】:
-
也许Spring Cache 可以在这里为您提供帮助。 Spring Cache 首先检查某个方法和键(可以自定义)的值是否可用,如果可用,将返回缓存命中而不输入方法。如果未命中,它将执行该方法并将返回值放入缓存中。挑战在于提供用户会话独有的密钥。
-
@RomanVottner 看起来很有希望。我现在刚刚放了cacheable注解,但是参数cacheNames不可用。我相信它在较新的版本中已被删除。注释应该够吗?
-
您可以在类级别通过
@CacheConfig(cacheNames="yourName", keyGenerator="customKeyGenerator", ...)声明cacheNames,只需用@Cacheable注释每个应该使用缓存的方法
标签: java spring spring-mvc spring-security