跳至主要內容

会话并发处理入门

Jin小于 1 分钟

会话并发处理入门

后登录的账号会使先登录的账号失效

自定义实现

public class MySessionInformationExpiredStrategy implements SessionInformationExpiredStrategy {
    @Override
    public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException, ServletException {
        //创建结果对象
        HashMap<String, Object> result = new HashMap<>();
        result.put("code", -1);
        result.put("message", "该账号已从其他设备登录");

        //转换成json字符串
        String json = JSON.toJSONString(result);

        HttpServletResponse response = event.getResponse();
        //返回响应
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
    }
}

自定义配置

        // 会话管理
        http.sessionManagement(session ->
                session.maximumSessions(1)
                        .expiredSessionStrategy(new MySessionInformationExpiredStrategy()));

测试

  • 打开Chrome 浏览器,登录成功

  • 打开 Edge 浏览器,登录成功

  • 访问 Chrome 其他请求,浏览器显示提示。

    • {
      code: -1,
      message: "该账号已从其他设备登录"
      }
      
贡献者: Jin