How to call long running blocking void returning method with Mutiny reactive programming?(如何用Mutiny反应式编程调用长时间运行的阻塞空返回方法?)
本文介绍了如何用Mutiny反应式编程调用长时间运行的阻塞空返回方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在Mutiny的UNI上有一个异步和同步方法调用链,有些方法是返回类型为void
的长时间运行的进程。
调用它们而不阻止下游的正确方式是什么?
下面是简单的类比代码。
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
并传递特定的执行程序:
longRunningMethodAsync
.runSubscriptionOn(executor);
请注意,它会将并发性限制为执行器中可用的线程数。
引用:
- https://smallrye.io/smallrye-mutiny/guides/emit-subscription
- https://smallrye.io/smallrye-mutiny/guides/emission-threads
这篇关于如何用Mutiny反应式编程调用长时间运行的阻塞空返回方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:如何用Mutiny反应式编程调用长时间运行的阻塞空


基础教程推荐
猜你喜欢
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 降序排序:Java Map 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01