1、flink实现计数器的灵感来源于Hadoop的MapReduce计算框架里的理念。

flink通过实现Accumulator接口实现并行计数。并行管理是由flink实现的。

public interface Accumulator<V, R extends Serializable> extends Serializable, Cloneable 

计数的结果通过JobExecutionResul的getAccumulatorResult方法t获取。

2、示例,在正常业务处理流程中对空字段计数,空字段包括null、空格、TAB等内容。这场景比较多见。

public class EmptyFieldsCountAccumulator {
private static final String EMPTY_FIELD_ACCUMULATOR= "empty-fields"; public static void main(String args[]) throws Exception{
final ParameterTool params = ParameterTool.fromArgs(args); final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment(); // make parameters available in the web interface
env.getConfig().setGlobalJobParameters(params); // get the data set
final DataSet<StringTriple> file = getDataSet(env, params); // filter lines with empty fields
final DataSet<StringTriple> filteredLines = file.filter(new EmptyFieldFilter()); // Here, we could do further processing with the filtered lines...
JobExecutionResult result;
// output the filtered lines
if (params.has("output")) {
filteredLines.writeAsCsv(params.get("output"));
// execute program
result = env.execute("Accumulator example");
} else {
System.out.println("Printing result to stdout. Use --output to specify output path.");
filteredLines.print();
result = env.getLastJobExecutionResult();
} // get the accumulator result via its registration key
final List<Integer> emptyFields = result.getAccumulatorResult(EMPTY_FIELD_ACCUMULATOR);
System.out.format("Number of detected empty fields per column: %s\n", emptyFields);
} @SuppressWarnings("unchecked")
private static DataSet<StringTriple> getDataSet(ExecutionEnvironment env, ParameterTool params) {
if (params.has("input")) {
return env.readCsvFile(params.get("input"))
.fieldDelimiter(";")
.pojoType(StringTriple.class);
} else {
System.out.println("Executing EmptyFieldsCountAccumulator example with default input data set.");
System.out.println("Use --input to specify file input.");
return env.fromCollection(getExampleInputTuples());
}
} private static Collection<StringTriple> getExampleInputTuples() {
Collection<StringTriple> inputTuples = new ArrayList<StringTriple>();
inputTuples.add(new StringTriple("John", "Doe", "Foo Str."));
inputTuples.add(new StringTriple("Joe", "Johnson", ""));
inputTuples.add(new StringTriple(null, "Kate Morn", "Bar Blvd."));
inputTuples.add(new StringTriple("Tim", "Rinny", ""));
inputTuples.add(new StringTriple("Alicia", "Jackson", " "));
inputTuples.add(new StringTriple("Alicia", "Jackson", " "));
inputTuples.add(new StringTriple("Alicia", "Jackson", " "));
inputTuples.add(new StringTriple("Tom", "Jackson", "A"));
inputTuples.add(new StringTriple("Amy", "li", "B "));
return inputTuples;
} /**
* This function filters all incoming tuples that have one or more empty fields.
* In doing so, it also counts the number of empty fields per attribute with an accumulator (registered under
* {@link EmptyFieldsCountAccumulator#EMPTY_FIELD_ACCUMULATOR}).
*/
public static final class EmptyFieldFilter extends RichFilterFunction<StringTriple> { // create a new accumulator in each filter function instance
// accumulators can be merged later on
private final VectorAccumulator emptyFieldCounter = new VectorAccumulator(); @Override
public void open(final Configuration parameters) throws Exception {
super.open(parameters); // register the accumulator instance
getRuntimeContext().addAccumulator(EMPTY_FIELD_ACCUMULATOR,
this.emptyFieldCounter);
} @Override
public boolean filter(final StringTriple t) {
boolean containsEmptyFields = false; // iterate over the tuple fields looking for empty ones
for (int pos = 0; pos < t.getArity(); pos++) { final String field = t.getField(pos);
if (field == null || field.trim().isEmpty()) {
containsEmptyFields = true; // if an empty field is encountered, update the
// accumulator
this.emptyFieldCounter.add(pos);
}
} return !containsEmptyFields;
}
} /**
* This accumulator maintains a vector of counts. Calling {@link #add(Integer)} increments the
* <i>n</i>-th vector component. The size of the vector is automatically managed.
* 这个向量计数器输入是整数,输出是List,并按字段位置计数,List里的索引就是字段计数位置,其值就是计数结果
*/
public static class VectorAccumulator implements Accumulator<Integer,ArrayList<Integer>>{
//存储计数器向量
private final ArrayList<Integer> resultVector; public VectorAccumulator() {
this(new ArrayList<>());
} public VectorAccumulator(ArrayList<Integer> resultVector) {
this.resultVector = resultVector;
} private void updateResultVector(int position,int delta){
//如果给出的位置不够就扩充向量容器
while (this.resultVector.size()<=position){
this.resultVector.add(0);
} final int component = this.resultVector.get(position);
this.resultVector.set(position,component+delta);
} //在指定位置加1
@Override
public void add(Integer position) {
updateResultVector(position,1);
} @Override
public ArrayList<Integer> getLocalValue() {
return this.resultVector;
} @Override
public void resetLocal() {
this.resultVector.clear();
} @Override
public void merge(Accumulator<Integer, ArrayList<Integer>> other) {
//合并两个向量计数器容器,按容器的索引合并
final ArrayList<Integer> otherVector = other.getLocalValue();
for(int i=0;i<otherVector.size();i++){
updateResultVector(i,otherVector.get(i));
}
} @Override
public Accumulator<Integer, ArrayList<Integer>> clone() {
return new VectorAccumulator(new ArrayList<>(this.resultVector));
} @Override
public String toString() {
return StringUtils.join(this.resultVector,':');
}
} public static class StringTriple extends Tuple3<String, String, String> { public StringTriple() {} public StringTriple(String f0, String f1, String f2) {
super(f0, f1, f2);
} } }
 

flink 并行计数器实现的更多相关文章

  1. 一文让你彻底了解大数据实时计算引擎 Flink

    前言 在上一篇文章 你公司到底需不需要引入实时计算引擎? 中我讲解了日常中常见的实时需求,然后分析了这些需求的实现方式,接着对比了实时计算和离线计算.随着这些年大数据的飞速发展,也出现了不少计算的框架 ...

  2. [源码解析] 当 Java Stream 遇见 Flink

    [源码解析] 当 Java Stream 遇见 Flink 目录 [源码解析] 当 Java Stream 遇见 Flink 0x00 摘要 0x01 领域 1.1 Flink 1.2 Java St ...

  3. Flink 的运行架构详细剖析

    1. Flink 程序结构 Flink 程序的基本构建块是流和转换(请注意,Flink 的 DataSet API 中使用的 DataSet 也是内部流 ).从概念上讲,流是(可能永无止境的)数据记录 ...

  4. C# Parallel.Invoke 实现

    Parallel.Invoke应该是Parallel几个方法中最简单的一个了,我们来看看它的实现,为了方法大家理解,我尽量保留源码中的注释: public static class Parallel ...

  5. Flink01

    1. 什么是Flink? 1.1 4代大数据计算引擎 第一代: MapReducer 批处理 Mapper, Reducer Hadoop的MapReducer将计算分为两个阶段, 分别为Map和Re ...

  6. Flink Program Guide (1) -- 基本API概念(Basic API Concepts -- For Java)

    false false false false EN-US ZH-CN X-NONE /* Style Definitions */ table.MsoNormalTable {mso-style-n ...

  7. Flink项目实战(一)---核心概念及基本使用

    前言.flink介绍: Apache Flink 是一个分布式处理引擎,用于在无界和有界数据流上进行有状态的计算.通过对时间精确控制以及状态化控制,Flink能够运行在任何处理无界流的应用中,同时对有 ...

  8. flink03-----1.Task的划分 2.共享资源槽 3.flink的容错

    1. Task的划分 在flink中,划分task的依据是发生shuffle(也叫redistrubute),或者是并行度发生变化 1.  wordcount为例 package cn._51doit ...

  9. Flink调优

      第1章 资源配置调优 Flink性能调优的第一步,就是为任务分配合适的资源,在一定范围内,增加资源的分配与性能的提升是成正比的,实现了最优的资源配置后,在此基础上再考虑进行后面论述的性能调优策略. ...

随机推荐

  1. Bitbucket与git上传源码的使用方法

    本文链接:https://blog.csdn.net/nomisshe/article/details/19625555 Bitbucket使用方法   一.软件及SSH keys: 由于我的Bitb ...

  2. [视频教程] 最新版swoole安装和TASKS功能测试

    今天我们来安装和测试一下php的多并发高性能网络通信扩展,这个扩展是使用C语音开发的,加载到PHP以后,在PHP的层面上实现了多并发异步通信,模拟了go语音的很多特性,极大的拓宽了PHP的应用场景. ...

  3. appium----Monkey测试

    做过app测试的应该都知道Monkey测试,今天简单的介绍下Monkey如何测试 什么是Monkey monkey测试的原理就是利用socket通讯的方式来模拟用户的按键输入,触摸屏输入,手势输入等, ...

  4. JSON理解(一篇就够了)

    可以看看视频讲解,视频几十分钟就结束了 JSON 1.什么是json 其实是一种数据格式的规范,与开发的语言无关,轻量级的数据格式 全称JavaScript Object Notation 2.优点: ...

  5. 解构如何运用的解构--报错 throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))

    let aa={ error_code: 0, reason: "插入数据成功" };//如何拿到 error_code 和 reason 的值 let { error_code, ...

  6. 【hdu3311】Dig The Wells(斯坦纳树+dp)

    传送门 题意: 给出\(n\)个重要点,还有其余\(m\)个点,\(p\)条边. 现在要在这\(n+m\)个点中挖几口水井,每个地方的费用为\(w_i\).连接边也有费用. 问使得这\(n\)个地点都 ...

  7. 初学Python几个小程序练习

    使用格式化输出的三种方式实现以下输出(name换成自己的名字,既得修改身高体重,不要厚颜无耻) name = 'ABDMLBM' height = 175 weight = 140 # "M ...

  8. Monkey小白入门篇

    一.monkey简介 中文名:猴子 职业:压力测试小工具 用途:对待测Android应用程序进行压力测试,测试app是否会crash Android官方描述: The Monkey is a prog ...

  9. web的前台、后台、前端、后端

    前台:呈现给用户的视觉和基本的操作.后台:用户浏览网页时,我们看不见的后台数据跑动.后台包括前端,后端.前端:对应我们写的html .javascript 等网页语言作用在前端网页.后端:对应jsp. ...

  10. Java代码精进

    一.代码命名规范 驼峰命名法(CamelCase) Google 定义了以下的转换规则: 从正常的表达形式开始,把短语转换成 ASCII 码,并且移除单引号. 例如,“Müller’s algorit ...