Spring事件发布应用
Healthy Mind Lv3

​ spring 事件机制的应用,在业务开发过程中很多时候会出现这样的需求,当系统创建一个任务的时候会有很多业务要做,比如我在项目中有一个这样的需求,创建一个数据映射任务配置之后,需要把这个任务上报到其他系统,在图库中创建相关的schema ,nifi 中需要创建任务流程等等这几个 步骤又各不相干;这个时候就可用使用事件发布机制。

​ 事件发布机制可用使用现成提供的,也可用自己实现,一下列几种以及实现好的

​ 1.jdk自带的观察者模式。

​ 2.guava包中实现的EventBus 可以标注到方法。

​ 3.spring ApplicationEventPublisher 实现,可以使用注解 @EventListener 也可以实现接口

我们可以根据自己项目中的情况选择,我这里是spring 项目就使用了spring 中提供的。

  1. 创建事件类 需要继承 ApplicationEvent
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class PimEvent extends ApplicationEvent {

private PimEventType eventType;

public PimEvent(Object source) {
super(source);
}

public PimEvent(Object source, PimEventType eventType) {
super(source);
this.eventType = eventType;
}

public PimEventType getEventType() {
return eventType;
}

public void setEventType(PimEventType eventType) {
this.eventType = eventType;
}

public enum PimEventType {
CREATE,UPDATE, DELETE;
}

}

2.创建监听类 只需要在方法上标注 @EventListener(PimEvent.class) 即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
@Component
public class GraphSchemaListener {

private static final Logger log = LoggerFactory.getLogger(GraphSchemaListener.class);

@Autowired
private GraphService graphService;

@EventListener(PimEvent.class)
public void onPimEvent(PimEvent event){
Object source = event.getSource();
if (source instanceof TPimConfig) {
if ( PimEventType.DELETE != event.getEventType() ) {
TPimConfig pimConfig = (TPimConfig) source;
boolean result = graphService.addOrCreateGraphSchema(pimConfig);
if (result) {
log.info("根据PIM[{}]创建图库schema成功!",pimConfig.getPimName());
}else {
log.error("根据PIM[{}]创建图库schema失败!",pimConfig.getPimName());
}
}
}
}

}


@Component
public class RegisterMetadataListener {

@Autowired
private IRegisterPimService registerPimService;

@EventListener(PimEvent.class)
public void onPimEvent(PimEvent event){
if (Boolean.valueOf(Configuration.getProperty("REGISTER_SWITCH"))) {
Object source = event.getSource();
if (source instanceof TPimConfig) {
if ( PimEventType.DELETE != event.getEventType() ) {
TPimConfig pimConfig = (TPimConfig) source;
try {
User user = UserContext.getLoginUser();
registerPimService.flowUnRegister(pimConfig.getPimName());
registerPimService.setProcessContent(pimConfig, null, pimConfig.getPimContent(),user);
registerPimService.flowRegister(pimConfig, null,user);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
}

3.发布事件 ApplicationEventPublisher 这个接口我们需要使用这个接口来发布一个事件

1
2
3
4
5
@Autowired
private ApplicationEventPublisher applicationEventPublisher;

//发布事件
applicationEventPublisher.publishEvent(new PimEvent(tPimConfig, PimEventType.CREATE));

很多时候,我们的业务是一点一点添加的,所以一开始我们可能不需要用到模式,只有当也需求改变到一定的量级的时候就需要我们去修改代码。