使用springboot 自带的事件发布订阅
1.首先定义事件模型
继承 org.springframework.context.ApplicationEvent;
public class AnEvent extends ApplicationEvent {
/**
* Create a new {@code ApplicationEvent}.
*
* @param source the object on which the event initially occurred or with
* which the event is associated (never {@code null})
*/
//自定义的传输模型(就是个普通的java实体)
private Entity source;
public AnEvent(Entity source) {
super(source);
this.source = source ;
}
@Override
public Object getSource() {
return this.source;
}
}
发送方
注入ApplicationEventPublisher
@Autowired
private ApplicationEventPublisher applicationEventPublisher;
//这里的entity 可以包含其他对象
applicationEventPublisher.publishEvent(new Entity("要传输的信息"));
接收方
//开启异步
@EnableAsync
@Async
@EventListener(Entity.class)
public void a(Entity entity) throws IOException {
System.out.println(entity.getMsg());
}
网友评论