springboot事件监听
一、定义事件
package com.base.common.event; import com.base.common.core.domain.entity.SysUser; import org.springframework.context.ApplicationEvent; public class MyCustomEvent extends ApplicationEvent { private SysUser user; public MyCustomEvent(Object source, SysUser user) { super(source); this.user = user; } public SysUser getUser() { return user; } }
二、定义事件监听
自定义异步方法写法:
package com.base.common.event;
import com.base.common.core.domain.entity.SysUser;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
@Slf4j
@Component
public class MyCustomEventListener {
@EventListener
@Async("threadPoolTaskExecutor")
public void onApplicationEvent(MyCustomEvent event) {
SysUser user = event.getUser();
try {
Thread.sleep(3000);
} catch (Exception e) {
e.printStackTrace();
}
log.info("bean-listener 收到了 publisher 发布的消息: " + user.getUserName());
}
}
实现ApplicationListener接口写法:
package com.base.common.event;
import com.base.common.core.domain.entity.SysUser;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
@Slf4j
@Component
@AllArgsConstructor
public class MyCustomEventListener implements ApplicationListener<MyCustomEvent> {
private final ThreadPoolTaskExecutor threadPoolTaskExecutor;
@Override
public void onApplicationEvent(MyCustomEvent event) {
threadPoolTaskExecutor.execute(() -> {
SysUser user = event.getUser();
try {
Thread.sleep(3000);
} catch (Exception e) {
e.printStackTrace();
}
log.info("bean-listener 收到了 publisher 发布的消息: " + user.getUserName());
});
}
}
三、发布事件
@Slf4j @RestController @RequestMapping("/system/user") @AllArgsConstructor public class SysUserController extends BaseController { private final ISysUserService userService; private final ApplicationContext context; @PostMapping("/send") public AjaxResult send() { String message = "发送成功"; SysUser sysUser = userService.selectUserById(1L); MyCustomEvent event = new MyCustomEvent(this, sysUser); context.publishEvent(event); return success(message); } }