- 在工作中,遇到了關於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";
}
}
有參考價值的相關博客地址
相關代碼下載
https://gitee.com/boxifeng/springdemo