spring 事件机制的简单封装

一、把消息的内容、主题以及事件发送者组建起来

import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

@Component
public class LocalEvent {
    private ApplicationEventPublisher publisher;
    private String topic;
    private Object content;

    public static LocalEvent builder(ApplicationEventPublisher publisher) {
        LocalEvent localEvent = new LocalEvent();
        localEvent.setPublisher(publisher);
        return localEvent;
    }

    public LocalEvent setTopic(String topic) {
        this.topic = topic;
        return this;
    }

    public LocalEvent setContent(Object content) {
        this.content = content;
        return this;
    }

    private void setPublisher(ApplicationEventPublisher publisher) {
        this.publisher = publisher;
    }

    public void publish() {
        publisher.publishEvent(this);
    }

    public String getTopic() {
        return topic;
    }

    public Object getContent() {
        return content;
    }

}

二、触发事件

 @Autowired
    private ApplicationEventPublisher publisher;
LocalEvent.builder(publisher)
                        .setTopic("message.order.deliver")
                        .setContent(new DeliverOrder(orderId, orderType))
                        .publish();

三、事件监听

@Component
public class OrderSubscriber {

    @Async
    @EventListener(condition = "#event.topic=='message.order.deliver'")
    public void onDeliver(LocalEvent event) throws BizException {
        DeliverOrder deliverOrder = (DeliverOrder) event.getContent();

        // TODO

        SystemLogger.info("订单[{}]发货成功", orderId);
    }
}

四、注意,这里使用了@Async异步注解,需要启用@EnableAsync;采用线程池技术,避免事件阻塞。
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
手动设置线程池的以下参数

private int corePoolSize = 1;
private int maxPoolSize = 2147483647;
private int keepAliveSeconds = 60;
private int queueCapacity = 2147483647;

以及饱和策略、线程名称。

你可能感兴趣的:(spring 事件机制的简单封装)