Apache flink 我可以在RichAsyncFunction中编写同步代码吗

Apache flink 我可以在RichAsyncFunction中编写同步代码吗,apache-flink,flink-streaming,Apache Flink,Flink Streaming,当我需要处理I/O(查询数据库,调用第三个API,…)时,我可以使用RichAsyncFunction。但我需要通过GG Sheet API与Google Sheet交互:。这个API是同步的。我写了以下代码片段: public class SendGGSheetFunction extends RichAsyncFunction<Obj, String> { @Override public void asyncInvoke(Obj message, final

当我需要处理I/O(查询数据库,调用第三个API,…)时,我可以使用RichAsyncFunction。但我需要通过GG Sheet API与Google Sheet交互:。这个API是同步的。我写了以下代码片段:

public class SendGGSheetFunction extends RichAsyncFunction<Obj, String> {

    @Override
    public void asyncInvoke(Obj message, final ResultFuture<String> resultFuture) {
        CompletableFuture.supplyAsync(() -> {
            syncSendToGGSheet(message);
            return "";
        }).thenAccept((String result) -> {
            resultFuture.complete(Collections.singleton(result));
        });
    }

}
公共类SendGGSheetFunction扩展了RichAsync函数{
@凌驾
公共void异步调用(Obj消息,最终结果未来结果未来){
CompletableFuture.SupplySync(()->{
syncSendToGGSheet(消息);
返回“”;
}).thenAccept((字符串结果)->{
resultFuture.complete(Collections.singleton(result));
});
}
}

但我发现发送到GGSheet的消息非常慢,似乎是通过同步发送的。

用户在
AsyncIO
中执行的大部分代码最初都是同步的。您只需要确保它实际上是在一个单独的线程中执行的。最常见的是使用(静态共享)
ExecutorService

private class SendGGSheetFunction extends RichAsyncFunction<Obj, String> {
   private transient ExecutorService executorService;

   @Override
   public void open(Configuration parameters) throws Exception {
      super.open(parameters);
      executorService = Executors.newFixedThreadPool(30);
   }

   @Override
   public void close() throws Exception {
      super.close();
      executorService.shutdownNow();
   }

   @Override
   public void asyncInvoke(final Obj message, final ResultFuture<String> resultFuture) {
      executorService.submit(() -> {
         try {
            resultFuture.complete(syncSendToGGSheet(message));
         } catch (SQLException e) {
            resultFuture.completeExceptionally(e);
         }
      });
   }
}
私有类SendGGSheetFunction扩展了RichAsyncFunction{
私人临时执行服务;
@凌驾
公共void open(配置参数)引发异常{
super.open(参数);
executorService=Executors.newFixedThreadPool(30);
}
@凌驾
public void close()引发异常{
super.close();
executorService.shutdownNow();
}
@凌驾
public void asyncInvoke(最终Obj消息,最终结果未来结果未来){
executorService.submit(()->{
试一试{
resultFuture.complete(syncsendtogsheet(message));
}捕获(SQLE异常){
结果:除(e)外,未来完成;
}
});
}
}

以下是关于如何优化AsyncIO以提高吞吐量的一些注意事项:

您将在这个邮件列表线程中找到一个示例:我找到了两种在asyncInvoke中实现的方法:
executorService.submit()
(和您一样)或
CompletableFuture.SupplySync(()->{executor.submit()})
。它们有何不同?
supplyAsync
使用共享JVM ForkJoinPool,您无法控制池大小。但它应该是,而不是使用
执行器