springboot的事件驱动

  • 在工作中,遇到了关于applicationEvent和EventListener相关的东西在这里做个记录

1、先创建一个登陆的事件event,需要继承applicationEvent,需要注意的是这个类不需要再进行@Component的操作

import org.springframework.context.ApplicationEvent;

/**
 * @author boxifeng
 * @version 1.0
 * @description:
 * @date 2020/10/11 18:10
 */
public class LoginEvent extends ApplicationEvent {
    public LoginEvent(Object source) {
        super(source);
    }
}

2、创建一个监听类。

  • 创建一个监听这个类的方法,加上@EventListener注解即可,参数是要监听的事件。
  • 需要将这个类添加到容器中@Component
  • 如果有两个监听器同时监听这一个相同事件 ,根据@Order注解确定先后执行顺序,数字小的先执行
@Component
public class LoginListener {
    @Order(40)
//    @Async
    @EventListener
    public void LoginLogListener(LoginEvent loginEvent) {
        System.out.println("这是LoginLogListener的线程名称"+Thread.currentThread().getName());
        Map map = (Map) loginEvent.getSource();
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("登陆成功,日志记录登陆用户名是" + map.get("username"));
    }
    @Order(30)
    @EventListener
//    @Async
    public void LoginMsgListener(LoginEvent loginEvent){
        System.out.println("这是LoginMsgListener的线程名称"+Thread.currentThread().getName());
        Map map = (Map) loginEvent.getSource();
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("给用户发送消息" + map.get("username"));
    }
}

3、创建一个controller进行发布事件测试

  • 要发布事件我们需要一个ApplicationContext,调用他的publishEvent方法,
    传入一个LoginEvent对象即可触发LoginEvent对象的监听器
@RestController
public class LoginController {
    @Autowired
    private ApplicationContext applicationContext;
    @GetMapping("/login/{username}")
    public String doLogin(@PathVariable String username){
        System.out.println("成功进入登录controller");
        Map<String, Object> map = new HashMap<>();
        map.put("username",username);
        applicationContext.publishEvent(new LoginEvent(map));
        System.out.println("这是controller");
        System.out.println("这是loginController的线程名称"+Thread.currentThread().getName());
        return "success";
    }

}

有参考价值的相关博客地址

  • 标题:Spring 面向事件驱动编程 https://zhuanlan.zhihu.com/p/85067174
  • 标题:Spring中不为人知的那些事 之《事件驱动》
    https://www.bilibili.com/video/BV1SE411d7Jh

相关代码下载

https://gitee.com/boxifeng/springdemo

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值