事件发布与订阅采用设计模式观察者模式

发布事件

/**
 * 事件发布应用程序
 *
 * @author wmhxx
 * @date 2021/11/13
 */
@Slf4j
public class EventReleaseApplication extends ApplicationEvent {


    /**
     * 事件发布应用程序
     *
     * @param source 源
     */
    public EventReleaseApplication(Object source) {
        super(source);
        log.info("事件发布:{}", source);
    }
}
/**
 * 事件控制器
 *
 * @author wmhxx
 * @date 2021/11/13
 */
@RestController
public class EventController {

    /**
     * 应用程序上下文
     */
    @Resource
    private ApplicationContext applicationContext;

    /**
     * 推动事件
     *
     * @return boolean
     */
    @PostMapping("/pushEvent")
    public boolean pushEvent() {
        applicationContext.publishEvent(new EventReleaseApplication("发布事件啦~~"));
        return true;
    }

}

订阅事件

/**
 * 应用程序事件侦听器
 *
 * @author wmhxx
 * @date 2021/11/13
 */
@Slf4j
@Component
public class EventApplicationListener {

    /**
     * 对应用程序event1
     *
     * @param event 事件
     */
    @Order(1)
    @EventListener
    public void onApplicationEvent1(EventReleaseApplication event) {
        log.info("{}[{}]:{}", Thread.currentThread().getName(), Thread.currentThread().getStackTrace()[1].getMethodName(), event.getSource());
        log.info("事件发生的时间:{}", event.getTimestamp());
    }


    /**
     * 对应用程序event2
     *
     * @param event 事件
     */
    @Order(2)
    @EventListener
    public void onApplicationEvent2(EventReleaseApplication event) {
        log.info("{}[{}}]:{}", Thread.currentThread().getName(), Thread.currentThread().getStackTrace()[1].getMethodName(), event.getSource());
        log.info("事件发生的时间:{}", event.getTimestamp());
    }


}
文章作者: 烦恼的夏洛克
版权声明: 本站所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 烦恼的夏洛克
Java Springboot
喜欢就支持一下吧