在我们的 Spring Boot Web 服务器中,我知道如何限制每个用户的 session (httpSecurity.sessionManagement().maximumSessions()
),但我想限制 session 总量,以避免服务器负载。
如何做到这一点?
最佳答案
如果“用户总数”是系统中“负载”的有意义的代理(请参阅@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));
但是,如果“用户总数”不是有意义的“负载”代理,那么您也许应该考虑以非阻塞方式实现您的服务,每个端点将其请求传递给线程池和请求到线程池的分配策略可以考虑请求的“重度”。轻量级请求可以由大型线程池处理,重型请求可以由较小线程池处理。
关于java - 限制 Spring Boot 应用程序中的 session 总量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46940813/