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都是数字
下面代码很好理解就不再解释了。
在这里插入图片描述
注意:由于我用的是IDEA+MAVEN的方式,打成jar包时默认是不会将src目录下的properties文件打到jar包里的,同时编译的时候properties文件也不会编译到相应的目录,需要在pom.xml文件添加如下内容,这样自定义的SortCounter.properties文件就会打包到对应目录,job ui页面才会正确显示。

<build>
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*</include>
            </includes>
        </resource>
    </resources>
</build>
发布了19 篇原创文章 · 获赞 0 · 访问量 700

猜你喜欢

转载自blog.csdn.net/qq_23120963/article/details/104326901