Spring-Security:优化获取当前经过身份验证的用户...

时间:2015-08-05 11:54:15

标签: java spring spring-mvc spring-security

我正在使用Spring-MVC应用程序,我在其中使用Spring-Security进行身份验证。由于过度使用获取当前经过身份验证的用户机制,Profiler将其显示为“分配热点”,并且单个用户消耗了近9.5kb内存。有没有办法优化这个基础设施。

PersonServiceImpl:

 @Override
    public Person getCurrentlyAuthenticatedUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            return null;
        } else {
            return personDAO.findPersonByUsername(authentication.getName());
        }
    }

如果我总是可以将用户从第一次检索后检索到的位置推送到某个缓存中,至少应该提高性能,但我不知道该怎么做。欢迎任何建议。感谢。

1 个答案:

答案 0 :(得分:0)

您可以使用某些变体。但你也可以尝试只使用Spring: 1.扩展org.springframework.security.core.userdetails.User并添加到UserEntity(Person)

public class User extends org.springframework.security.core.userdetails.User {
    private Person sysUser; 

  public User(Person sysUser) {
        super(sysUser.getLogin(), sysUser.getPassword(), new ArrayList<>());
        this.sysUser = sysUser;
    }

public Person getYourUser(){
return sysUser;
}

}
  1. 使用您的用户实体和扩展的org.springframework.security.core.userdetails.User实现UserDetailsS​​ervice

    @Service(value = "userService")
    public class UserService implements UserDetailsService {
    @Autowired
    SecurityDAO securityDAO;
    
    @Override
    public UserDetails loadUserByUsername(String login) throws UsernameNotFoundException {
        User user = null;
        try {
            Person su = securityDAO.getUserOnlyByLogin(login);
            if (su != null)
                user = new User(Person);
    
        } catch (Exception e) {
    
            e.printStackTrace();
        }
    
    
        return user;
    }
    

    }

  2. 配置Spring(xml或Annotation):

  3.  <beans:bean id="userService" class="your.pack.UserService"/>
        <authentication-manager alias="authenticationManager">
            <authentication-provider user-service-ref="userService"/>
        </authentication-manager>
    
    1. 使用您的方法

      @覆盖

         public Person getCurrentlyAuthenticatedUser() {
              Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
      
              if (authentication == null) {
                  return null;
              } else {  User user = (User) authentication.getPrincipal();
                  return user.getYourUser();
              }
          }