@Component public class EventDistributor implements ApplicationEventPublisherAware { private static ApplicationEventPublisher applicationEventPublisher; @Override public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { EventDistributor.applicationEventPublisher = applicationEventPublisher; } /** * 发布同步事件 * @param event 事件主题 */ public static void publishEvent(ApplicationEvent event) { try { applicationEventPublisher.publishEvent(event); }catch (Exception e){ e.printStackTrace(); System.out.println("事件发布成功,有部分执行失败"); } } /** * 发布异步事件,会等待当前事务提交完成后再进行事件发布 * @param event 事件主题 */ public static void publishTransactionSyncEvent(ApplicationEvent event) { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCommit() { try{ applicationEventPublisher.publishEvent(event); }catch (Exception e){ e.printStackTrace(); } } }); } }
public class TicketAddEvent extends ApplicationEvent { public TicketAddEvent(ClienteleTicketMessage userTicketMessage) { super(userTicketMessage); } }
在需要被监听处使用:
EventDistributor.publishEvent(new TicketAddEvent(参数));
@Component public class TicketOverviewListener implements ApplicationListener<TicketAddEvent> { @Async//异步 @Override public void onApplicationEvent(TicketAddEvent ticketAddEvent) { ClienteleTicketMessage userTicketMessage = (ClienteleTicketMessage) ticketAddEvent.getSource();//接受参数 响应逻辑 }
监听完成