您好,登錄后才能下訂單哦!
package com.sky.mr.wordcount;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import org.junit.Test;
import java.io.IOException;
public class WordcountMapper extends Mapper<LongWritable,Text, Text, IntWritable> {
//由于每讀一行文本數(shù)據(jù),就要調用一次map方法,為了避免多次創(chuàng)建對象,浪費內(nèi)存資源,將Text,IntWritable對象創(chuàng)建在
//map方法之外
Text k = new Text();
IntWritable v = new IntWritable(1);
@Override
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
//獲取每一行的文本內(nèi)容
String line = value.toString();
//按空格分割
String[] words = line.split(" ");
//轉換數(shù)據(jù)格式,輸出
for ( String word: words) {
k.set(word);
context.write(k, v);
}
}
}
package com.sky.mr.wordcount;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
import java.io.IOException;
public class WordcountReducer extends Reducer<Text, IntWritable, Text,IntWritable> {
IntWritable v = new IntWritable();
@Override
protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
//求每組相同key的總個數(shù)
int sum = 0;
for ( IntWritable count:values) {
sum += count.get();
}
//輸出
v.set(sum);
context.write(key, v);
}
}
package com.sky.mr.wordcount;
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.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import java.io.IOException;
public class WordcountDriver {
public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
//1、獲取配置信息以及job對象
Configuration conf = new Configuration();
Job job = Job.getInstance(conf);
//2、設置jar包路徑
job.setJarByClass(WordcountDriver.class);
//3、關聯(lián)自定義mapper和reducer類
job.setMapperClass(WordcountMapper.class);
job.setReducerClass(WordcountReducer.class);
//4、設置Map輸出key和value類型
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(IntWritable.class);
//5、設置最終結果key,value類型
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
//6、設置文件輸入輸出路徑
FileInputFormat.setInputPaths(job,new Path(args[0]));
FileOutputFormat.setOutputPath(job,new Path(args[1]));
//7、將封裝了MapReduce程序運行參數(shù)的job對象,提交到Yarn集群
boolean result = job.waitForCompletion(true);
System.exit(result?0:1);
}
}
import org apache hadoop io
import org apache hadoop io
import org apache hadoop
import java io IOException
IOException 1
apache 3
hadoop 3
import 4
io 3
java 1
org 3
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。