Apache flink 如何正确实现HTTP接收器?
我想通过HTTP协议将数据流的计算结果发送给其他服务。我看到了两种可能的实施方法:Apache flink 如何正确实现HTTP接收器?,apache-flink,flink-streaming,Apache Flink,Flink Streaming,我想通过HTTP协议将数据流的计算结果发送给其他服务。我看到了两种可能的实施方法: 在接收器中使用同步Apache HttpClient客户端 公共类SyncHttpSink扩展了RichSink函数{ 私有静态最终字符串URL=”http://httpbin.org/post"; 私有可关闭httpClient httpClient; 私有直方图httpStatusesAccumulator; @凌驾 公共void open(配置参数)引发异常{ httpClient=HttpClients.
公共类SyncHttpSink扩展了RichSink函数{
私有静态最终字符串URL=”http://httpbin.org/post";
私有可关闭httpClient httpClient;
私有直方图httpStatusesAccumulator;
@凌驾
公共void open(配置参数)引发异常{
httpClient=HttpClients.custom()
.setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.INSTANCE)
.build();
httpStatusesAccumulator=getRuntimeContext().getHistogram(“http_状态”);
}
@凌驾
public void close()引发异常{
httpClient.close();
httpStatusesAccumulator.resetLocal();
}
@凌驾
公共void调用(SessionItem值)引发异常{
List params=new ArrayList();
add(新的BasicNameValuePair(“session_uid”,value.getSessionUid());
add(新的BasicNameValuePair(“traffic”,String.valueOf(value.getTraffic())));
add(新的BasicNameValuePair(“duration”,String.valueOf(value.getDuration()));
UrlEncodedFormEntity实体=新的UrlEncodedFormEntity(参数,Consts.UTF_8);
HttpPost HttpPost=新的HttpPost(URL);
httpPost.setEntity(实体);
try(CloseableHttpResponse-response=httpClient.execute(httpPost)){
int httpStatusCode=response.getStatusLine().getStatusCode();
httpStatusesAccumulator.add(httpStatusCode);
}
}
}
公共类AsyncHttpSink扩展了RichSink函数{
私有静态最终字符串URL=”http://httpbin.org/post";
私有可关闭HttpAsyncClient httpClient;
私有直方图httpStatusesAccumulator;
@凌驾
公共void open(配置参数)引发异常{
httpClient=HttpAsyncClients.custom()
.setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.INSTANCE)
.build();
httpClient.start();
httpStatusesAccumulator=getRuntimeContext().getHistogram(“http_状态”);
}
@凌驾
public void close()引发异常{
httpClient.close();
httpStatusesAccumulator.resetLocal();
}
@凌驾
公共void调用(SessionItem值)引发异常{
List params=new ArrayList();
add(新的BasicNameValuePair(“session_uid”,value.getSessionUid());
add(新的BasicNameValuePair(“traffic”,String.valueOf(value.getTraffic())));
add(新的BasicNameValuePair(“duration”,String.valueOf(value.getDuration()));
UrlEncodedFormEntity实体=新的UrlEncodedFormEntity(参数,Consts.UTF_8);
HttpPost HttpPost=新的HttpPost(URL);
httpPost.setEntity(实体);
执行(httpPost,newfuturecallback(){
@凌驾
公共无效已完成(HttpResponse响应){
int httpStatusCode=response.getStatusLine().getStatusCode();
httpStatusesAccumulator.add(httpStatusCode);
}
@凌驾
公共作废失败(例外情况除外){
httpStatusesAccumulator.add(-1);/-1-失败
}
@凌驾
公众假期取消(){
httpStatusesAccumulator.add(-2);//-2-已取消
}
});
}
}
问题:
RuntimeContext
不是线程安全的,因此必须同步对它的访问