• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

尼古拉斯豆

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

Hadoop中的计数器

计数器的典型应用是用来跟踪不同的输入记录类型,特别是跟踪“坏”记录。

http://blog.csdn.net/dajuezhao/archive/2010/08/04/5788705.aspx

 

一、环境

1、hadoop 0.20.2

2、操作系统Linux

二、背景

1、最近写MR的代码,总在想统计一些错误的数据出现的次数,发现如果都写在reduce的输出里太难看了,所以想找办法专门输出一些统计数字。

2、翻看《hadoop权威指南》第8章第1节的时候发现能够自定义计数器,但都是基于0.19版本写的,好多函数都不对,改动相对较大。

3、基于上面2个理由,写个文档,记录一下。

三、实现

1、前提:写入一个文件,规范的是3个字段,“\t”划分,有2条异常,一条是2个字段,一条是4个字段,内容如下:

jim    1 28

kate  0 26

tom   1

lily     0 29 22

2、统计处不规范的数据。我没有写reduce,因为不需要输出,代码如下,先看代码

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Counter;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;

public class MyCounter {

public static class MyCounterMap extends Mapper<LongWritable, Text, Text, Text> {

public static Counter ct = null;

protected void map(LongWritable key, Text value,
org.apache.hadoop.mapreduce.Mapper<LongWritable, Text, Text, Text>.Context context)
throws java.io.IOException, InterruptedException {
String arr_value[] = value.toString().split("\t");
if (arr_value.length > 3) {
ct = context.getCounter("ErrorCounter", "toolong"); //ErrorCounter为组名,toolong为组员名
ct.increment(1); //计数器加一
} else if (arr_value.length < 3) {
ct = context.getCounter("ErrorCounter", "tooshort");
ct.increment(1);
}
}
}

public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
Configuration conf = new Configuration();
String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
if (otherArgs.length != 2) {
System.err.println("Usage: MyCounter <in> <out>");
System.exit(2);
}

Job job = new Job(conf, "MyCounter");
job.setJarByClass(MyCounter.class);

job.setMapperClass(MyCounterMap.class);

FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));
System.exit(job.waitForCompletion(true) ? 0 : 1);
}



 
4、各个map的计数器在最后阶段会有hadoop自动对它们进行求和。
 
5、这些计数器的数值会在JobTracker的Web用户界面中与Hadoop的内部计数器一起显示。

四、总结

1、其实hadoop权威指南写的很清楚了,但是由于版本不一样,所以很多方法也不同,总一下,主要有以下不同:不再需要枚举的类型、计数器名不在需要写properties文件,调用的方法在context中都封装了。

2、hadoop权威指南中写了统计百分比值,代码改改就能实现,就是一个总数除以错误数然后百分比的结果。

posted on 2012-03-27 16:02  尼古拉斯豆  阅读(268)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3