gpt4 book ai didi

java - 如何编写Vertx worker verticle - 无限期阻塞操作?

转载 作者:行者123 更新时间:2023-12-02 10:11:38 26 4
gpt4 key购买 nike

下面的类是我的工作垂直体,我想在其中从名为 events-config 的 channel 上的事件总线接收消息时执行阻塞代码。

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

我正在使用executeBlocking 来实现所需的功能。然而,由于我无限期地运行阻塞操作,vertx 阻止了线程检查器转储警告。

问题:
- 有没有办法只对特定的verticle禁用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
}
}

}

最佳答案

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

使用vertx.setPeriodic()vertx.setTimer()代替:

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

关于java - 如何编写Vertx worker verticle - 无限期阻塞操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54966699/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com