基于HttpSessionListener实现限制在线用户数量
作者:互联网
/** * @Author: lizhang10 * @Date: 2019/6/26 09:49 * @Description:创建session的时候userCounts加1存入redis,session销毁的时候减1存进redis */ public class MyHttpSessionListener implements HttpSessionListener { //当前用户数 private int userCounts=0; @Override public void sessionCreated(HttpSessionEvent se) { //创建session 用户数+1 userCounts++; //保存在线有用户数到redis RedisTemplate redisTemplate = null; redisTemplate = SpringUtil.getBean("redisTemplate" , RedisTemplate.class); redisTemplate.opsForValue().set("userCounts",String.valueOf(userCounts)); } @Override public void sessionDestroyed(HttpSessionEvent se) { //session销毁 用户数-1 userCounts--; //保存在线有用户数到redis RedisTemplate redisTemplate = null; redisTemplate = SpringUtil.getBean("redisTemplate" , RedisTemplate.class); redisTemplate.opsForValue().set("userCounts",String.valueOf(userCounts)); }
//查询redis userCounts数量大于5000就提示现在高峰期过一会登陆 String userCount = redisTemplate.opsForValue().get("userCounts").toString(); if (Integer.parseInt(userCount) > 5000) { attr.addFlashAttribute("msg", SysCode.LoginMsg.USER_COUNT);}else{ ...... }
标签:在线,redis,RedisTemplate,session,用户数,HttpSessionListener,userCounts,用户数量,redisTemp 来源: https://www.cnblogs.com/AnonymouL/p/11090265.html