Spring事件驱动模型实践

简介

Spring的事件驱动模型,是发布/订阅模式(Publish–subscribe pattern)的实现,或者简单的称之为发布/订阅模式(Publish–subscribe pattern)。主要包括以下几类角色:

  • 事件(ApplicationEvent):需要处理的event本身,继承自Java自身的EventObject
  • 发布者(ApplicationEventPublisher):事件的发布者,用它进行事件的发布
  • 广播(ApplicationEventMulticaster):类似于发布/订阅模式(Publish–subscribe pattern)中Broker的一个概念,负责event存储管理及event的广播
  • 订阅者(ApplicationListener):监听广播出来的不同类别的event

实现

event

1
2
3
4
5
6
public class TestEvent extends ApplicationEvent {

public TestEvent(String message) {
super(message);
}
}

publisher

BasePublisher

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Component
public class BasePublisher implements ApplicationEventPublisherAware {

private ApplicationEventPublisher applicationEventPublisher;

@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
if (Objects.isNull(this.applicationEventPublisher)) {
this.applicationEventPublisher = applicationEventPublisher;
}
}

public void publish(Object o) {
this.applicationEventPublisher.publishEvent(o);
}
}

TestPublisher

1
2
3
4
5
6
7
8
9
10
11
@Component
public class TestEventPublisher extends BasePublisher {

/**
* Simulate an event on application start
*/
@PostConstruct
public void init() {
this.publish(new TestEvent("test-message"));
}
}

TestListener

1
2
3
4
5
6
7
8
9
@Slf4j
@Component
public class TestListener implements ApplicationListener<TestEvent> {

@Override
public void onApplicationEvent(TestEvent testEvent) {
log.error("receive event:{}", testEvent.getSource());
}
}

运行结果

文章作者: DongyangHu
文章链接: http://hudongyang.com/2020/01/09/spring-event-driven/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Sunshine