私は自分の非同期カスタムメソッドをVert.xでコードに似たものを作成しようとしています:
// call the external service
WebClient client = WebClient.create(vertx);
client.get(8080, "localhost:8080", "/fast").send(ar -> {
if (ar.succeeded()) {
HttpResponse<Buffer> response = ar.result();
System.out.println("response.bodyAsString()" + response.bodyAsString());
} else {
System.out.println("Something went wrong " + ar.cause().getMessage());
}
});
このコードを実行すると、所有者スレッドをブロックせずにスレッドがスリープ状態になり、エンドポイントが応答すると、提供されたハンドラーが実行されます。
「executeBlocking」、「createSharedWorkerExecutor.executeBlocking」を使用してバスを使用する方法を見つけましたが、それらすべてでスレッドがブロックされます。
コンテナースレッドをブロックせずにそれを行う方法を探していますが、見つかりません。投稿があります:
私はそれをやろうとしましたが、それもスレッドをブロックします:
vertx.runOnContext(v -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
handler.handle(Future.succeededFuture("result"));
});
上記のコードは同じスレッドで実行されますが、同時には実行されないため、スレッドがブロックされていると思います。
それを行う方法はありますか?
呼び出す方法はThread.sleep()
、現在のJVMスレッドをスリープ状態にして、同じスレッドで実行される現在のvert.xイベントループを効果的にブロックします。これは、vert.xでブロックコードを実行する慣用的な方法ではありません。
ここを参照してください:「ゴールデンルール-イベントループをブロックしないでください」。
などのブロッキングコードを実行する必要がある場合はThread.sleep()
、ワーカーバーティクルを使用してそのコードを実装する必要があります。ワーカーバーティクルは、別のスレッドプールのJVMスレッドを使用するため、イベントループをブロックしません。
上記で投稿した最初のコード例では、あなた自身が正しく説明したように、ブロッキングコードを使用していません。非同期の非ブロッキングイベントハンドラーで慣用的な方法を使用します。
編集する
非常に単純なワーカーバーティクルを開始する方法のこの短い例を参照してください。
クラスからのコードは、WorkerVerticle
イベントループを決してブロックしません。に示されているように正しいオプションを設定することにより、バーティクルの展開中にそれをワーカーにしますDeployerVerticle
。
public class DeployerVerticle extends AbstractVerticle {
@Override
public void start() throws Exception {
System.out.println("Main verticle has started, let's deploy another...");
// Deploy it as a worker verticle
vertx.deployVerticle("io.example.WorkerVerticle",
new DeploymentOptions().setWorker(true));
}
}
// ----
package io.example;
/**
* An example of a worker verticle
*/
public class WorkerVerticle extends AbstractVerticle {
@Override
public void start() throws Exception {
System.out.println("[Worker] Starting in " +
Thread.currentThread().getName());
// consume event bus messages sent to address "sample.data"
// reply with incoming message transformed to upper case
vertx.eventBus().<String>consumer("sample.data", message -> {
Thread.sleep(1000); // will not block the event loop
// but only this verticle
System.out.println("[Worker] Consuming data in " +
Thread.currentThread().getName());
String body = message.body();
message.reply(body.toUpperCase());
});
}
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加