本文介紹了如何用Mutiny反應(yīng)式編程調(diào)用長時間運行的阻塞空返回方法?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
我在Mutiny的UNI上有一個異步和同步方法調(diào)用鏈,有些方法是返回類型為void
的長時間運行的進(jìn)程。
調(diào)用它們而不阻止下游的正確方式是什么?
下面是簡單的類比代碼。
class Root {
public static void main(String[] args) {
final Response response = getResponsePayload(); // Gets the the Payload from upstream service
Uni.createFrom().item(response)
.onItem().invoke(() -> System.out.println("Process Started"))
.onItem().call(res -> {
longRunningMethodAsync(res); // long running blocking method, I want to run on a worker thread
return Uni.createFrom().voidItem(); // This line I created, because of the ppipeline will be broken if the Uni is not returned from here
})
.onItem().transform(item -> item.hello + " mutiny")
.onItem().transform(String::toUpperCase)
.subscribe().with(
item -> System.out.println(">> " + item)); // This is printed to the console
}
// Boilerplate method - I created to invoke/call the actual method actual method - `longRunningMethod`, this method basically an adapter
// This is the best apprach I could come up, but I'm looking for better thatn this as I'm not conviced I'm doing it right
private static UniSubscribe<Void> longRunningMethodAsync(final Response response) {
return Uni.createFrom().voidItem().invoke(() -> longRunningMethod(response))
.runSubscriptionOn(Infrastructure.getDefaultExecutor()).subscribe();
}
// Important - this is the method I want to run asynchronously independently of main *event-loop* thread.
private static void longRunningMethod(final Response response) {
System.out.println("Long running process started"); // Doesn't get printed, which means this is never called at all, not even in the blocked manner by the main even-loop thread
}
// Not as importatnt, I provded this in case if you like to run on your local box
private static Response getResponsePayload() {
return new Response();
}
private static class Response {
public final String hello = "hello";
}
}
推薦答案
通常使用runSubscriptionOn
并傳遞特定的執(zhí)行程序:
longRunningMethodAsync
.runSubscriptionOn(executor);
請注意,它會將并發(fā)性限制為執(zhí)行器中可用的線程數(shù)。
引用:
https://smallrye.io/smallrye-mutiny/guides/emit-subscription
https://smallrye.io/smallrye-mutiny/guides/emission-threads
這篇關(guān)于如何用Mutiny反應(yīng)式編程調(diào)用長時間運行的阻塞空返回方法?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,