如何编写Vertx工人verticle-无限阻塞操作?

时间:2019-03-03 07:52:12

标签: java vert.x vertx-verticle vertxoptions

下面的类是我的工作程序垂直目录,在其中我希望在名为events-config的通道上从事件总线接收消息时执行阻塞代码。

目标是无限期生成和发布json消息,直到我在events-config通道上收到停止操作消息为止。

我正在使用executeBlocking实现所需的功能。但是,由于是无限期地运行阻止操作,因此vertx阻止了threadchecker转储警告。

问题:
-是否有一种方法仅对特定的Version禁用blockedthreadchecker?
-下面的代码是否遵循在vertx中根据需要执行无限循环的最佳实践?如果不能,请建议最好的方法吗?

public class WorkerVerticle extends AbstractVerticle {

    Logger logger = LoggerFactory.getLogger(WorkerVerticle.class);

    private MessageConsumer<Object> mConfigConsumer;
AtomicBoolean shouldPublish = new AtomicBoolean(true);
private JsonGenerator json = new JsonGenerator();

    @Override
    public void start() {
        mConfigConsumer = vertx.eventBus().consumer("events-config", message -> {
            String msgBody = (String) message.body();
            if (msgBody.contains(PublishOperation.START_PUBLISH.getName()) && !mJsonGenerator.isPublishOnGoing()) {
                logger.info("Message received to start producing data onto kafka " + msgBody);
                vertx.<Void>executeBlocking(voidFutureHandler -> {
                    Integer numberOfMessagesToBePublished = 100000;
                    if (numberOfMessagesToBePublished <= 0) {
                        logger.info("Skipping message publish :"+numberOfMessagesToBePublished);
                        return; // is it best way to do it ??
                    }
                    publishData(numberOfMessagesToBePublished);
                },false, voidAsyncResult -> logger.info("Blocking publish operation is terminated"));

            } else if (msgBody.contains(PublishOperation.STOP_PUBLISH.getName()) && mJsonGenerator.isPublishOnGoing()) {
                logger.info("Message received to terminate " + msgBody);
                mJsonGenerator.terminatePublish();
            }
        });
    }

private void publishData(){
  while(shouldPublish.get()){
   //code to generate json indefinitely until some one reset shouldPublish variable
}
}

}

1 个答案:

答案 0 :(得分:1)

您不想在异步代码中使用繁忙循环。

改为使用vertx.setPeriodic()vertx.setTimer()

vertx.setTimer(20, (l) -> {
    // Generate your JSON
    if (shouldPublish.get()) {
       // Set timer again
    }
});