怎么用Mutiny反应式编程调用长时间运行的阻塞空返回方法?

原学程将引见若何用Mutiny反响式编程挪用长时光运转的壅塞空前往办法?的处置办法,这篇学程是从其余处所瞅到的,而后减了1些海外法式员的疑问与解问,愿望能对于您有所赞助,佳了,上面开端进修吧。

怎么用Mutiny反应式编程调用长时间运行的阻塞空返回方法? 教程 第1张

成绩描写

我在Mutiny的UNI上有1个异步以及同步办法挪用链,有些办法是前往典型为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反响式编程挪用长时光运转的壅塞空前往办法?的学程便到这里便停止了,愿望趣模板源码网找到的这篇技巧文章能赞助到年夜野,更多技巧学程不妨在站内搜刮。