使用flink进行数据处理时,我们经常会需要跟外部系统交换,比如查询mysql。每一条数据都访问一次外部系统,等待响应,再往下执行,这种等待会占用很大一部分数据处理时间。为此flink提供了异步IO API,异步访问外部系统,并行处理,同时响应,节省访问等待时间。采用flink做实时数仓基本会使用异步io api去join维表。
下面通过一个简单的demo介绍下异步IO API使用方法:
使用异步io 需要继承RichAsyncFunction类,这里没有真正访问外部数据:
public class Asyncdata extends RichAsyncFunction<Integer,String>{
@Override
public void asyncInvoke(Integer integer, ResultFuture<String> resultFuture) throws Exception {
CompletableFuture.supplyAsync(new Supplier<String>() {
@Override
public String get() {
try {
return "test";
} catch (Exception e) {
// Normally handled explicitly.
return null;
}
}
}).thenAccept( (String result) -> {
// resultFuture.completeExceptionally(new Exception("wawawa"));
resultFuture.complete(Collections.singleton(integer.intValue()+","+result));
});
}
@Override
public void timeout(Integer input, ResultFuture<String> resultFuture) throws Exception {
//请求超时处理
}
@Override
public void open(Configuration parameters) throws Exception {
}
@Override
public void close() throws Exception {
}
}
public class FlinkAsyncIO {
public static void main(String[] args) throws Exception {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
DataStreamSource<Integer> ds = env.fromElements(1, 2, 3);
SingleOutputStreamOperator<String> so = AsyncDataStream.unorderedWait(ds, new Asyncdata(), 1000, TimeUnit.MILLISECONDS, 10);
so.print();
env.execute();
}
}