MapReduce全局程序计数器Counters
Counters定义
Counters represent global counters, defined either by the MapReduce framework or applications. Each Counter can be of any Enum type. Counters of a particular Enum are bunched into groups of type Counters.Group.
Applications can define arbitrary Counters (of type Enum) and update them via Counters.incrCounter(Enum, long) or Counters.incrCounter(String, String, long) in the map and/or reduce methods. These counters are then globally aggregated by the framework.
Counters 是全局计数器,由MapReduce框架或者Application定义。每一个Counter可以是任何枚举类型。特定计数器按枚举类型进行分组。
用户可以在map/reduce方法里通过context.getCounter(Enum<?> counterName)
来获取定义好的计数器。
然后通过counter.increment(long incr)
的方式计数。
MapReduce框架本身就提供了很多内置的计数器,如File System Counters、Job Counters、Map-Reduce Framework、File Input Format Counters、File Output Format Counters。可在运行MR任务后的控制台打印信息里看到,如下图。其中SecondarySort Counters是自定义的Counter,不是MR自带的。
也可通过在ResourceManager的web页面上查看job的具体信息中得知,如下图
我们可以发现如Map-Reduce Framework是一个Counter Group,Map input records
就是Map-Reduce Framework
这个Counter Group的一个具体的Counter。
以源码的TaskCounter计数器为例
我们以源码中org.apache.hadoop.mapreduce.TaskCounter
这个CounterGroup为例,源码如下
TaskCounter.java所在源码目录下有一个对应的TaskCounter.properties文件 ,该properties文件是用来为TaskCounter这个CounterGroup做资源绑定的,简单来说就是做显示用的。
ResourceBundle properties file for Map-Reduce counters
如下图就是TaskCounter.properties文件的内容,和web页面显示的是一样的。
properties文件的命名以enum文件名一样,CounterGroupName就是该CounterGroup在页面上显示的CounterGroup名字。
每个具体的enum如何绑定显示名字呢?以MAP_INPUT_RECORDS为例,MAP_INPUT_RECORDS.name=Map input records
就能改变其对应的显示名字。
自定义Counter例子
新建SortCounter.java
枚举类,内容如下
新建SortCounter.properties
文件,内容如下
运行MR任务后会看到如下信息,在ResourceManager的web页面也能查看
在map方法里使用到了自定义计数器,left和right都是数字
下面代码很好理解就不再解释了。