spring boot 1使用spring-reactor EventBus

一、引入spring的jar

<dependency>
            <groupId>io.projectreactor</groupId>
            <artifactId>reactor-core</artifactId>
        </dependency>
        <dependency>
            <groupId>io.projectreactor</groupId>
            <artifactId>reactor-bus</artifactId>
        </dependency>
<!-- spring对reactor的使用进行了二次封装 -->
        <dependency>
            <groupId>io.projectreactor.spring</groupId>
            <artifactId>reactor-spring-context</artifactId>
        </dependency>

二、定义本地消息事件接口和实现类
两个属性:主题和内容

public interface LocalEvent {
    String getTopic();
    Object getContent();  
}
import com.google.common.base.Strings;
import org.springframework.stereotype.Component;
import reactor.bus.Event;
import reactor.bus.EventBus;

/**
 * 本地消息事件
 * 
 */
@Component
public class LocalMessageEvent implements LocalEvent {
         private EventBus eventBus; 

       private String topic;

       private Object content;
    
      public static LocalMessageEvent builder(EventBus eventBus){
        LocalMessageEvent me= new LocalMessageEvent();
        me.setEventBus(eventBus);
        return me;
    }
     
     public void dispatch() {
        eventBus.notify(topic.trim(), Event.wrap(content));
    }

    public EventBus getEventBus() {
        return eventBus;
    }

    public LocalMessageEvent setEventBus(EventBus eventBus) {
        this.eventBus = eventBus;
        return this;
    }

    public LocalMessageEvent() {
    }

    public LocalMessageEvent(String topic, Object content) {
        this.topic = topic;
        this.content = content;
    }

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

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

    public String getTopic() {
        return topic;
    }

    public Object getContent() {
        return content;
    }}

三、发布事件

@Autowired
 private EventBus eventBus;

LocalMessageEvent.builder(eventBus)
                .setTopic("xxx")
                .setContent(content).dispatch();

四、订阅事件

@Consumer
public class OrderListenerHandler {
     @Autowired
    private EventBus eventBus;

   // 订阅主题xxx
   @Selector("xxx")
    public void onEvent(String msg) {
            // 处理业务代码
    }
}
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容