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