我对Vertx很陌生,但我对测试它与Spring的集成非常感兴趣。我使用Spring启动来增强项目,并部署了两个Verticle。我希望他们使用事件总线相互通信,但失败了。这就是我所做的:
在主要应用程序中:
@SpringBootApplication 公共类MySpringVertxApplication { @Autowired MyRestAPIServer myRestAPIServer; @Autowired MyRestAPIVerticle MyRestAPIVerticle;
public static void main(String[] args) {
SpringApplication.run(MySpringVertxApplication.class, args);
}
@PostConstruct
public void deployVerticles(){
System.out.println("deploying...");
Vertx.vertx().deployVerticle(MyRestAPIVerticle);
Vertx.vertx().deployVerticle(myRestAPIServer);
}
}
在APIVerticle:
@Component 公共类MyRestAPIVerticle扩展AbstractVerticle {
public static final String ALL_ACCOUNT_LISTING = "com.example.ALL_ACCOUNT_LISTING";
@Autowired
AccountService accountService;
EventBus eventBus;
@Override
public void start() throws Exception {
super.start();
eventBus = vertx.eventBus();
MessageConsumer<String> consumer = eventBus.consumer(MyRestAPIVerticle.ALL_ACCOUNT_LISTING);
consumer.handler(message -> {
System.out.println("I have received a message: " + message.body());
message.reply("Pretty Good");
});
consumer.completionHandler(res -> {
if (res.succeeded()) {
System.out.println("The handler registration has reached all nodes");
} else {
System.out.println("Registration failed!");
}
});
}
}
最后是ServerVerticle:
@服务 公共类MyRestAPIServer扩展了AbstractVerticle {
HttpServer server;
HttpServerResponse response;
EventBus eventBus;
@Override
public void start() throws Exception {
server = vertx.createHttpServer();
Router router = Router.router(vertx);
eventBus = vertx.eventBus();
router.route("/page1").handler(rc -> {
response = rc.response();
response.setChunked(true);
eventBus.send(MyRestAPIVerticle.ALL_ACCOUNT_LISTING,
"Yay! Someone kicked a ball",
ar->{
if(ar.succeeded()){
System.out.println("Response is :"+ar.result().body());
}
}
);
});
server.requestHandler(router::accept).listen(9999);
}
但是在我启动它并访问/ page1之后,消息无法从ServerVerticle发送到APIVerticle。如果我将事件总线使用者移动到与发件人相同的Verticle中,则可以接收事件。
这两个Verticle之间发送消息有什么不对吗?我怎样才能使它发挥作用?
提前致谢。
答案 0 :(得分:0)
您将它们部署在单独的vertx实例中:
Vertx.vertx().deployVerticle(MyRestAPIVerticle);
Vertx.vertx().deployVerticle(myRestAPIServer);
试试这个:
Vertx vertx = Vertx.vertx();
vertx.deployVerticle(MyRestAPIVerticle);
vertx.deployVerticle(myRestAPIServer);
答案 1 :(得分:0)
Vertx事件总线不会像您尝试的那样在不同的Vertx实例之间共享(但是群集的Vert.x应用程序可以做到)。在您的情况下,请将其更改为使用单个Vert.x实例,例如下面的MySpringVertxApplication
。
Vertx vertx = Vertx.vertx();
vertx.deployVerticle(MyRestAPIVerticle.class.getName());
vertx.deployVerticle(MyRestAPIServer.class.getName());