美文网首页
spring boot 1使用spring-reactor Ev

spring boot 1使用spring-reactor Ev

作者: 天草二十六_简村人 | 来源:发表于2018-11-17 13:58 被阅读0次

一、引入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) {
            // 处理业务代码
    }
}

相关文章

网友评论

      本文标题:spring boot 1使用spring-reactor Ev

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