springboot使用监听器实现用户在线离线状态的监控

520也依旧勤奋的写着代码,我真是太勤勉了

实现了用户登录的监听器,实时监听session,以此控制数据库中用户的登录状态

本来在监听器上同时加入了@Component@WebListener,随后监听器便运行了两次,便去掉了@WebListener注解

以下是完整的监听器代码:

package com.video.listener;

import com.video.service.UserLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

@Component
//@WebListener
public class UserLoginListener implements HttpSessionListener, ServletContextListener {

    private ServletContext application = null;

    @Autowired
    private UserLoginService userLoginService;

    public void contextDestroyed(ServletContextEvent s) {
        System.out.println("context Destroyed");
    }

    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("context init");
        application = sce.getServletContext();
        Set<String> onlineUserSet = new HashSet<>();
        application.setAttribute("onlineUserSet", onlineUserSet);
    }

    public void sessionCreated(HttpSessionEvent se) {

        System.out.println("session create");
    }

    public void sessionDestroyed(HttpSessionEvent se) {
        HttpSession session = se.getSession();
        Set<String> onlineUserSet = (Set<String>)application.getAttribute("onlineUserSet");
        String userId = (String)session.getAttribute("userId");
        onlineUserSet.remove(userId);
        application.setAttribute("onlineUserSet",onlineUserSet);

        //设置离线状态
        int rows = userLoginService.setOffline(userId);
        if(rows>0){
            System.out.println("离线成功");
        }
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(formatter.format(date));
        onlineUserSet = (Set<String>)application.getAttribute("onlineUserSet");
        System.out.println("当前在线用户:"+onlineUserSet.toString());
        System.out.println(userId + "-->超时退出");
    }

}

这是登录功能代码:

@RequestMapping("/login")
    @ResponseBody
    public MsgResponse login(String number, String password,
                             Integer check, HttpServletRequest request){

        User user = userLoginService.checkLogin(number,password,check);

        //验证失败返回
        if (user==null){
            return MsgResponse.error("账号或密码错误");
        }
        HttpSession session = request.getSession();
        ServletContext application = session.getServletContext();
        //验证成功
        //将用户信息添加到session当中
        session.setAttribute("user",user);
        String userId = user.getUserId();
        //设置状态为离线
        int rows = userLoginService.setOnline(userId);
        //获取当前时间
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //将用户名信息加到application当中

        session.setAttribute("userId", userId);
        Set<String> onlineUserSet = (Set)application.getAttribute("onlineUserSet");
        onlineUserSet.add(userId);
        application.setAttribute("onlineUserSet", onlineUserSet);
        //输出用户登录情况到控制台
        System.out.println(formatter.format(date));
        System.out.println("用户:"+userId+"已登录");
        System.out.println("当前在线用户:"+onlineUserSet.toString());
        return MsgResponse.success("登录成功",null);
    }

同时还需要在启动器上加上@ServletComponentScan注解

配置文件properties中可以设置session的超时时间,为了测试效果,这里用了十秒钟

server.servlet.session.timeout=10s

这样便完成了监听器对session的在线离线状况的监控!

 我真是太勤勉了,晚安!

  • 4
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring Boot中使用监听器可以通过实现`ApplicationListener`接口来实现。下面是一个简单的示例: 首先,创建一个自定义监听器类,实现`ApplicationListener`接口,并指定监听的事件类型。例如,我们创建一个监听器类`MyEventListener`来监听`ApplicationStartedEvent`事件: ```java import org.springframework.boot.context.event.ApplicationStartedEvent; import org.springframework.context.ApplicationListener; public class MyEventListener implements ApplicationListener<ApplicationStartedEvent> { @Override public void onApplicationEvent(ApplicationStartedEvent event) { System.out.println("应用程序已启动!"); // 在这里可以添加自定义的逻辑 } } ``` 然后,在Spring Boot应用程序的主类中注册监听器。可以使用`SpringApplication.addListeners()`方法来添加监听器: ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class MyApplication { public static void main(String[] args) { SpringApplication app = new SpringApplication(MyApplication.class); app.addListeners(new MyEventListener()); // 注册自定义监听器 app.run(args); } } ``` 这样,在应用程序启动时,`MyEventListener`中的`onApplicationEvent()`方法就会被调用。 除了`ApplicationStartedEvent`,Spring Boot还提供了其他一些常用的事件,例如`ApplicationReadyEvent`、`ContextRefreshedEvent`等,你可以选择适合你需求的事件类型来监听。 希望以上信息能对你有帮助!如果还有其他问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值