限制Sprint Boot应用程序中的会话总数

时间:2017-10-25 19:40:18

标签: java spring spring-boot load session-management

在我们的Spring Boot Web服务器中,我知道如何限制每个用户的会话数(httpSecurity.sessionManagement().maximumSessions()),但我想限制会话总数,以避免服务器上的负载。

如何做到这一点?

1 个答案:

答案 0 :(得分:1)

如果“用户总数”是系统中“加载”的有意义代理(请参阅@JBNizet的评论),例如如果大多数请求在资源占用方面相同,那么您可以定义自己的SessionAuthenticationStrategy实现。这是一个简单的例子:

private class AllUsersConcurrentSessionControlAuthenticationStrategy extends ConcurrentSessionControlAuthenticationStrategy {

    // probably inject this from application configuration
    private final int maxUsers;
    private final SessionRegistry sessionRegistry;

    public AllUsersConcurrentSessionControlAuthenticationStrategy(int maxUsers, SessionRegistry sessionRegistry) {
        super(sessionRegistry);
        this.maxUsers = maxUsers;
        this.sessionRegistry = sessionRegistry;
    }

    @Override
    public void onAuthentication(Authentication authentication, HttpServletRequest request,
                                 HttpServletResponse response) {
        if (sessionRegistry.getAllPrincipals().size() > maxUsers) {
            throw new SessionAuthenticationException("...");
        }
        super.onAuthentication(authentication, request, response);
    }
}

你这样注册:

http.sessionManagement().sessionAuthenticationStrategy(new AllUsersConcurrentSessionControlAuthenticationStrategy(maxUsers, sessionRegistry));

但是,如果“用户总数”是“加载”的有意义代理,那么您应该考虑以非阻塞方式实施服务,每个端点都将其请求传递给线程池和请求到线程池分配策略可以考虑请求的“重”程度。轻量级请求可以由大型线程池处理,重量级请求可以由较小的线程池处理。