hadoop编程小技巧(2)---计数器Counter,hadoopcounter


Hadoop代码测试版本:2.4

应用场景:在Hadoop编程的时候,有时我们在进行我们算法逻辑的时候想附带了解下数据的一些特性,比如全部数据的记录数有多少,map的输出有多少等等信息(这些是在算法运行完毕后,直接有的),就可以使用计数器Counter。

如果是针对很特定的数据的一些统计,比如统计以1开头的所有记录数等等信息,这时就需要自定义Counter。自定义Counter有两种方式,第一种,定义枚举类型,类似:

public enum MyCounters{
		ALL_RECORDS,ONE_WORD_lINE
	}
然后在需要计数的地方使用:

cxt.getCounter(MyCounters.ONE_WORD_lINE).increment(1); // one way to increase the records

第二种方法,使用字符串,在需要使用计数的时候直接使用:

cxt.getCounter("MyCounters_String", "One Word In a Line").increment(1);// the another way to increase the records

这样也可以对特定条件的数据进行计数。
实例:自定义Counter统计每行数据只含有一个单词的数据记录数;

使用《hadoop编程小技巧(1)---map端聚合》的代码,在其中添加下面的代码

public enum MyCounters{
		ALL_RECORDS,ONE_WORD_lINE
	}
	
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		ToolRunner.run(new Configuration(), new InMapArrgegationDriver(),args);
	}

protected void map(LongWritable key, Text value,Context cxt){
			String  [] line = value.toString().split(" "); // use blank to split
			if(line.length==1){
				cxt.getCounter(MyCounters.ONE_WORD_lINE).increment(1); // one way to increase the records
				cxt.getCounter("MyCounters_String", "One Word In a Line").increment(1);// the another way to increase the records
			}
			for(String word:line){
				Word curr = new Word(word,1);
				if(words.contains(curr)){
					// increase the exists word's frequency
					for(Word w:words){
						if(w.equals(curr)){
							w.frequency++;
							break;
						}
					}
				}else{
					words.add(curr);
				}
			}
		}

由于输入中有三行数据是只有一个单词的,所以上面统计的结果应该是3,查看输出信息:


这里可以看到自定义的枚举类型的Counter ,MyCounters.ONE_WORD_lINE 以及字符串定义的 One Word In a Line 统计得到的结果都是3;


总结:使用Counter可以在不影响程序原始逻辑的基础上,统计数据的信息,不过个人感觉用处不是很大。


分享,成长,快乐

转载请注明blog地址:http://blog.csdn.net/fansy1990



(2) 试编写Java代码实现一个计数器类Counter,其中包含:

public class Counter{
private int counterValue=0;

public void setCounterValue(String counterValue){
this.counterValue=counterValue;
}

public int getCounterValue(){
return this.counterValue;
}

public void increment(){
getCounterValue()+1;
}

public void decrement(){
getCounterValue()-1;
}

public void reset(){
this.setCounterValue(0);
}
}

这段代码我没有编译,你自己试一下看行不行
这里没有写main()方法,至于你说的定义几个构造函数的话,要看你想要做什么,你可以在写构造方法的时候给这个变量赋值

只供你参考用
 

Hadoop 20专题

密码是什么
 

相关内容

    暂无相关文章