Шина событий Vertx не может отправлять сообщение в другую версталью

Я новичок в Vertx, но мне очень интересно протестировать его интеграцию со Spring. Я использовал Spring boot для ускорения проекта и развернул две версии. Я хочу, чтобы они общались друг с другом с помощью шины событий, но не удалось. Вот что я сделал:

  1. В основном приложении:

    @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);
    }
    

    }

  2. В статье:

    Открытый класс @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!");
        }
      });
    }
    

    }

  3. Наконец сервер

    Открытый класс @Service 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. Если я переместил потребителя шины событий в ту же вертикаль, что и отправитель, то событие может быть получено.

Здесь что-то не так с отправкой сообщения между двумя статьями? Как заставить его работать?

Заранее спасибо.


person user3006967    schedule 06.03.2016    source источник


Ответы (2)


Вы развернули их в отдельном экземпляре vertx:

Vertx.vertx().deployVerticle(MyRestAPIVerticle);
Vertx.vertx().deployVerticle(myRestAPIServer);

Попробуй это:

Vertx vertx = Vertx.vertx();
vertx.deployVerticle(MyRestAPIVerticle);
vertx.deployVerticle(myRestAPIServer);
person cy3er    schedule 09.03.2016

Шина событий Vertx не является общей для разных экземпляров Vertx, как вы пытаетесь (но кластерные приложения Vert.x могут это сделать). В вашем случае измените его, чтобы использовать один экземпляр Vert.x, как показано ниже в вашем MySpringVertxApplication.

Vertx vertx = Vertx.vertx();
vertx.deployVerticle(MyRestAPIVerticle.class.getName());
vertx.deployVerticle(MyRestAPIServer.class.getName());
person Hegdekar    schedule 29.11.2018