11-23每日博客

Mapreduce实例——求平均值
求平均数是MapReduce比较常见的算法,求平均数的算法也比较简单,一种思路是Map端读取数据,在数据输入到Reduce之前先经过shuffle,将map函数输出的key值相同的所有的value值形成一个集合value-list,然后将输入到Reduce端,Reduce端汇总并且统计记录数,然后作商即可。具体原理如下图所示:

编写Java代码运行Mapreduce程序:
package exper;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.NullWritable;
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.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;

public class MyAverage {
public static class Map extends Mapper<Object, Text, Text, IntWritable> {
private static Text newKey = new Text();

public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
String line = value.toString();
System.out.println(line);
String arr[] = line.split(" ");
newKey.set(arr[0]);
int click = Integer.parseInt(arr[1]);
context.write(newKey, new IntWritable(click));
}
}

public static class Reduce extends Reducer<Text, IntWritable, Text, IntWritable> {
public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
int num = 0;
int count = 0;
for (IntWritable val : values) {
num += val.get();
count++;
}
int avg = num / count;
context.write(key, new IntWritable(avg));
}
}

public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
Configuration conf = new Configuration();
System.out.println("start");
Job job = new Job(conf, "MyAverage");
job.setJarByClass(MyAverage.class);
job.setMapperClass(Map.class);
job.setReducerClass(Reduce.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
job.setInputFormatClass(TextInputFormat.class);
job.setOutputFormatClass(TextOutputFormat.class);
String InPath="D:\\mapreduce\\2in\\goods_click.txt";
String OutPath="file:///D:/mapreduce/2out";
FileInputFormat.addInputPath(job,new Path(InPath));
FileOutputFormat.setOutputPath(job,new Path(OutPath));
System.exit(job.waitForCompletion(true) ? 0 : 1);

}
}

posted @ 2021-11-23 21:27  软工新人  阅读(92)  评论(0编辑  收藏  举报