Vert.x 是高度模块化的,各模块之间通过EventBus进行通信。EventBus提供发布订阅功能和点对点的消息服务,远程服务调用就是通过EventBus的点对点消息服务实现的。
每条消息在EventBus上都有一个地址,发布者向这个地址发送消息,接收者从这个地址接收消息。
SenderVerticle.java
import io.vertx.core.AbstractVerticle;
public class SenderVerticle extends AbstractVerticle {
@Override
public void start() throws Exception {
/*
.publish 会将消息传递给所有在地址上注册过的处理器
.send 只会将消息传递给该地址注册的其中一个处理器
*/
vertx.eventBus().send("edu.abc.hello", "hello world!", res -> {
if (res.succeeded()){
System.out.println("received reply : " + res.result().body());
}
});
//vertx.eventBus().publish("edu.abc.hello", "hello world!");
}
@Override
public void stop() throws Exception {
super.stop();
}
}
ReceiverVerticle.java
import io.vertx.core.AbstractVerticle;
import io.vertx.core.eventbus.EventBus;
import io.vertx.core.eventbus.MessageConsumer;
public class ReceiverVerticle extends AbstractVerticle {
@Override
public void start() throws Exception {
EventBus eb = vertx.eventBus();
MessageConsumer<String> consumer = eb.consumer("edu.abc.hello");
consumer.handler( message -> {
System.out.println("received message : " + message.body().toString());
});
MessageConsumer<String> consumer1 = eb.consumer("edu.abc.hello");
consumer1.handler( message -> {
System.out.println("received message1 : " + message.body().toString());
});
}
@Override
public void stop() throws Exception {
super.stop();
}
}
Main
public static void main(String[] args) {
Vertx vertx = Vertx.vertx();
vertx.deployVerticle(new ReceiverVerticle());
vertx.deployVerticle(new SenderVerticle());
}
Vert.x 的核心组件EventBus提供了发布订阅和点对点的消息服务,用于模块间通信。通过消息地址,发布者可以发送消息,而接收者则能监听并接收对应地址的消息。EventBus也是实现远程服务调用的基础。

2119

被折叠的 条评论
为什么被折叠?



