介绍
ApplicationEvent类似于MQ,是Spring提供的一种发布订阅模式的事件处理方式。相对于MQ,其局限在于只能在同一个Spring容器中使用。
使用步骤
封装消息
将要发送的内容,封装成一个bean,这个bean需要继承ApplicationEvent类。
package com.example.event;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.context.ApplicationEvent;
/**
* @Description: 封装消息
* @author: zeal
* @date: 2024年04月09日 10:22
*/
@Setter
@Getter
@ToString
public class UserLoginEvent extends ApplicationEvent {
private Integer userId;
private String token;
public UserLoginEvent(Object source,Integer userId,String token) {
super(source);
this.userId=userId;
this.token=token;
}
}
推送消息
推送消息时,注入ApplicationEventPublisher或ApplicationContext均可,调用publishEvent()方法。
package com.example.event;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @Description: 消息推送
* @author: zeal
* @date: 2024年04月09日 10:26
*/
@RestController
@RequestMapping("event")
public class UserLoginController {
@Autowired
private ApplicationContext applicationContext;
@RequestMapping("/push")
public void pushEvent(){
UserLoginEvent userLoginEvent=new UserLoginEvent(this,001,"zsaf");
applicationContext.publishEvent(userLoginEvent);
}
}
监听消息
此步骤相当于MQ的消费者,实现ApplicatonListener类,通过泛型来设置消息类型。
package com.example.event;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
/**
* @Description: 监听消息
* @author: zeal
* @date: 2024年04月09日 10:25
*/
@Component
public class UserLoginEventListener implements ApplicationListener<UserLoginEvent> {
@Override
public void onApplicationEvent(UserLoginEvent event) {
System.out.println("收到消息:"+event.toString());
}
}
通过注解实现监听
package com.example.event;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
/**
* @Description: 监听消息
* @author: zeal
* @date: 2024年04月09日 10:25
*/
@Component
public class UserLoginEventListener{
@EventListener
public void onApplicationEvent(UserLoginEvent event) {
System.out.println("收到消息:"+event.toString());
}
}