hadoop从wordCount开始
最近一段时间大数据很火,我有稍微有点java基础,自然选择了由java编写的hadoop框架,wordCount是hadoop中类似于java中helloWorld的存在,自然不能错过。
package hadoop.wordcount.com;
import java.io.IOException;
import java.util.StringTokenizer;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
public class WordCount {
/**
* Hadoop mapreduce中的map,用来把数据转化为map
* @author admin
*
*/
public static class TokenizerMapper
extends Mapper<Object, Text, Text, IntWritable>{
// IntWritable是hadoop中定义的类型,相当于java中的int,这行代码相当于 int one=1;
private final static IntWritable one = new IntWritable(1);
// Text是hadoop中定义的类型,相当于java中的String,这行代码相当于 String text="";
private Text word = new Text();
/**
* hadoop中继承Mapper需要实现map()方法
* key 转化为map时输入的key,类型与Mapper第一个参数一致
* value 转化为map时输入的value,类型与Mapper第二个参数一致
*/
public void map(Object key, Text value, Context context
) throws IOException, InterruptedException {
StringTokenizer itr = new StringTokenizer(value.toString());
// 遍历输入的value,并将它们写入上下文
while (itr.hasMoreTokens()) {
word.set(itr.nextToken());
context.write(word, one);
}
}
}
/**
* hadoop mapreduce中的Reducer,对数据的具体操作写在这里面
* @author admin
*
*/
public static class IntSumReducer
extends Reducer<Text,IntWritable,Text,IntWritable> {
private IntWritable result = new IntWritable();
/**
* 在这里添加对数据的操作
* key为输入类型
* values为输出类型
*
*/
public void reduce(Text key, Iterable<IntWritable> values,
Context context
) throws IOException, InterruptedException {
int sum = 0;
for (IntWritable val : values) {
sum += val.get();
}
result.set(sum);
context.write(key, result);
}
}
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();// 读取配置文件
Job job = Job.getInstance(conf, "word count");// 新建一个任务
job.setJarByClass(WordCount.class);// 主类
job.setMapperClass(TokenizerMapper.class);// mapper
job.setCombinerClass(IntSumReducer.class);
job.setReducerClass(IntSumReducer.class);// reducer
job.setOutputKeyClass(Text.class);// 输出结果的key类型
job.setOutputValueClass(IntWritable.class);// 输出结果的value类型
// 要读取的数据,此处内容根据你hadoop实际配置而定
FileInputFormat.addInputPath(job, new Path("hdfs://dtj007:9000/dtj007/djt.txt"));
// 要输出数据的路径,此处内容根据你hadoop实际配置而定
FileOutputFormat.setOutputPath(job, new Path("hdfs://dtj007:9000/dtj007/wordcount-out"));
System.exit(job.waitForCompletion(true) ? 0 : 1);// 提交任务
}
}
运行完毕以后可以在你linux配置的hadoop目录下使用:
bin/hadoop fs -text /你在wordCount中配置的输出路径/part-r-00000
命令进行查看

浙公网安备 33010602011771号