美文网首页
Springboot- EventPublisher

Springboot- EventPublisher

作者: 尼尔君 | 来源:发表于2020-09-12 23:38 被阅读0次

使用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());
    }

相关文章

网友评论

      本文标题:Springboot- EventPublisher

      本文链接:https://www.haomeiwen.com/subject/xewgektx.html