1.项目结构如下
2.首先先定义一个消息事件
/**
* Created by Jujung
* Date : 2019/8/18 22:42
*/
@Data
public class MessageEvent extends ApplicationEvent {
private long postId;
private long fromUserId;
private long toUserId;
private int event;
public MessageEvent(Object source) {
super(source);
}
}
3.定义一个消息事件的监听器
/**
* Created by Jujung
* Date : 2019/8/18 22:47
*/
@Slf4j
@Component
public class MessageEventHandler implements ApplicationListener<MessageEvent> {
/**
* 处理事件的方法
*
* @param event
*/
@Async // 开启异步处理
@Override
public void onApplicationEvent(MessageEvent event) {
log.info("------------> {}", event.toString());
}
}
4.在程序中注册事件
/**
* Created by Jujung
* Date : 2019/8/18 22:53
*/
@Slf4j
@RequestMapping("/user")
@RestController
public class UserController {
@Autowired
private UserService userService;
@Autowired
private ApplicationContext applicationContext;
@GetMapping("/{id}")
public TbUser user(@PathVariable Long id){
return userService.selectById(id);
}
/**
* 在applicationContext中注册事件
*/
@GetMapping("/event")
public void event(){
MessageEvent event = new MessageEvent(this);
event.setPostId(1L);
event.setFromUserId(1L);
applicationContext.publishEvent(event);
TbUser user = userService.selectById(1L);
log.info("---------->{}",user.toString());
}
}
因为我们定义的事件监听方法为异步方法,所以还要开启异步方法功能
@EnableAsync
@SpringBootApplication
public class Learn3Application {
public static void main(String[] args) {
SpringApplication.run(Learn3Application.class, args);
}
}
5.最后启动项目在浏览器中访问http://localhost:8080/user/event
可在日志中看到监听器已经监听到消息
2019-08-19 10:03:39.580 INFO 7660 --- [ task-2] c.j.common.event.MessageEventHandler : ------------> MessageEvent(postId=1, fromUserId=1, toUserId=0, event=0)
2019-08-19 10:03:39.582 INFO 7660 --- [nio-8080-exec-4] com.jujung.controller.UserController : ---------->TbUser(id=1, userName=jerry, passWord=123456, gender=1, telephoneNum=18530018297)