public class LoginEvent extends ApplicationEvent {
private final String userName;
public LoginEvent(Object source, String username) {
super(source);
this.userName = username;
}
public String getUserName() {
return userName;
}
}
@Service
public class LoginEventPublisher {
private final ApplicationEventPublisher applicationEventPublisher;
public LoginEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.applicationEventPublisher = applicationEventPublisher;
}
public void publishLoginEvent(String username) {
LogonEvent loginEvent = new LoginEvent(this, username);
applicationEventPublisher.publishEvent(loginEvent);
}
}
// 日志处理事件监听器
@Component
public class LoginEventPrintLogListener {
@EventListener
public void handleUserLoginEvent(LoginEvent event) {
String username = event.getUserName();
// 在这里执行处理用户登录事件的逻辑,例如记录日志或触发其他操作
System.out.println("User logged in: " + username);
}
}
// 登录消息通知事件监听器
@Component
public class LoginEventMessageNoticeListener {
@EventListener
public void LoginEventMessageNoticeListener(LoginEvent event) {
String username = event.getUserName();
// 发送消息通知用户
System.out.println("message send User logged in: " + username);
}
}
@Component
public class MyCommandLineRunner implements CommandLineRunner {
private final LoginEventPublisher loginEventPublisher;
public MyCommandLineRunner(LoginEventPublisher loginEventPublisher) {
this.loginEventPublisher = loginEventPublisher;
}
@Override
public void run(String... args) {
// 在应用程序启动后执行的自定义逻辑
System.out.println("MyCommandLineRunner executed!");
// 登录成功
// 登录执行后逻辑
loginEventPublisher.publishLoginEvent("小王");
}
}
2023-10-13 16:04:02.021 INFO 5356 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1250 ms
2023-10-13 16:04:02.382 INFO 5356 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2023-10-13 16:05:31.792 INFO 5356 --- [ main] c.e.s.SpringBootTestMavenApplication : Started SpringBootTestMavenApplication in 200.49 seconds (JVM running for 201.165)
MyCommandLineRunner executed!
message send User logged in: 小王
User logged in: 小王
// 日志处理事件监听器
@Component
public class LoginEventPrintLogListener {
@EventListener
public void handleUserLoginEvent(LoginEvent event) {
String username = event.getUserName();
// 在这里执行处理用户登录事件的逻辑,例如记录日志或触发其他操作
System.out.println("User logged in: " + username);
}
}
// 登录消息通知事件监听器
@Component
public class LoginEventMessageNoticeListener {
@EventListener
public void LoginEventMessageNoticeListener(LoginEvent event) {
String username = event.getUserName();
// 发送消息通知用户
System.out.println("message send User logged in: " + username);
}
}
@Component
public class LoginEventPrintLogListenerTest implements ApplicationListener<LoginEvent> {
@Override
public void onApplicationEvent(LoginEvent event) {
System.out.println("this is a Listener with not annotation");
}
}
@SpringBootApplication
// 开启 Async
@EnableAsync
public class SpringBootTestMavenApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootTestMavenApplication.class, args);
}
}
@Component
public class LoginEventPrintLogListener {
@EventListener
// 配置任务异步 创建新线程处理该事件
@Async
public void handleUserLoginEvent(LoginEvent event) throws Exception {
String username = event.getUserName();
// 在这里执行处理用户登录事件的逻辑,例如记录日志或触发其他操作
System.out.println("User logged in: " + username);
}
}
@Component
public class LoginEventPrintLogListener {
@EventListener(condition = "#event.userName.equals('小王')")
public void handleUserLoginEvent(LoginEvent event) throws Exception {
String username = event.getUserName();
// 在这里执行处理用户登录事件的逻辑,例如记录日志或触发其他操作
System.out.println("User logged in: " + username);
}
}
方案一:将事务处理逻辑和事件发布拆分,避免上述异常场景(推荐)
方案二:使用 TransactionalEventListener 指定和事务执行的顺序关系
@Component
public class MyCommandLineRunner implements CommandLineRunner {
private final RegisterEventPublisher registerEventPublisher;
public MyCommandLineRunner(RegisterEventPublisher registerEventPublisher) {
this.RegisterEventPublisher = registerEventPublisher;
}
@Override
@Transactional
public void run(String... args) {
// 在应用程序启动后执行的自定义逻辑
System.out.println("MyCommandLineRunner executed!");
// 注册成功
// 注册执行后逻辑
registerEventPublisher.publishRegisterEvent("小王");
// 执行异常导致事务回滚
}
}
@Component
public class RegisterEventPrintLogListener {
// 事务提交后才会执行
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
public void handleUserRegisterEvent(RigisterEvent event) throws Exception {
String username = event.getUserName();
// 在这里执行处理用户注册事件的逻辑,例如记录日志或触发其他操作
System.out.println("User register: " + username);
}
}
@Component
public class LoginEventPrintLogListener {
@EventListener
@Order(1)
public void handleUserLoginEvent(LoginEvent event) throws Exception {
String username = event.getUserName();
// 在这里执行处理用户登录事件的逻辑,例如记录日志或触发其他操作
System.out.println("User logged in: " + username);
}
}
@Component
public class LoginEventMessageNoticeListener {
@EventListener
@Order(2)
public void LoginEventMessageNoticeListener(LoginEvent event) {
String username = event.getUserName();
// 发送消息通知用户
System.out.println("message send User logged in: " + username);
}
}
public class GenericEvent<T> extends ApplicationEvent {
private T eventData;
public GenericEvent(Object source, T eventData) {
super(source);
this.eventData = eventData;
}
public T getEventData() {
return eventData;
}
}
@Service
public class EventPublisherService {
private final ApplicationEventPublisher eventPublisher;
public EventPublisherService(ApplicationEventPublisher eventPublisher) {
this.eventPublisher = eventPublisher;
}
public <T> void publishGenericEvent(T eventData) {
GenericEvent<T> genericEvent = new GenericEvent<>(this, eventData);
eventPublisher.publishEvent(genericEvent);
}
}
@Component
public class GenericEventListener {
@EventListener
public <T> void handleGenericEvent(GenericEvent<T> event) {
T eventData = event.getEventData();
System.out.println("Received a generic event with data: " + eventData);
}
}
@Component
public class MyErrorHandler implements ErrorHandler {
@Override
public void handleError(Throwable t) {
log.info("handle error -> {}", t.getClass());
}
}
@Service
public class EventListenerService {
@Autowired
private SimpleApplicationEventMulticaster simpleApplicationEventMulticaster;
@Autowired
private MyErrorHandler errorHandler;
@PostConstruct
public void init(){
simpleApplicationEventMulticaster.setErrorHandler(errorHandler);
}
}
@Configuration
public class AsyncConfig implements AsyncConfigurer {
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new SimpleAsyncUncaughtExceptionHandler();
}
}
👋 你好,我是 Lorin 洛林,一位 Java 后端技术开发者!座右铭:Technology has the power to make the world a better place.
🚀 我对技术的热情是我不断学习和分享的动力。我的博客是一个关于Java生态系统、后端开发和最新技术趋势的地方。
🧠 作为一个 Java 后端技术爱好者,我不仅热衷于探索语言的新特性和技术的深度,还热衷于分享我的见解和最佳实践。我相信知识的分享和社区合作可以帮助我们共同成长。
💡 在我的博客上,你将找到关于Java核心概念、JVM 底层技术、常用框架如Spring和Mybatis 、MySQL等数据库管理、RabbitMQ、Rocketmq等消息中间件、性能优化等内容的深入文章。我也将分享一些编程技巧和解决问题的方法,以帮助你更好地掌握Java编程。
🌐 我鼓励互动和建立社区,因此请留下你的问题、建议或主题请求,让我知道你感兴趣的内容。此外,我将分享最新的互联网和技术资讯,以确保你与技术世界的最新发展保持联系。我期待与你一起在技术之路上前进,一起探讨技术世界的无限可能性。
📖 保持关注我的博客,让我们共同追求技术卓越。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。