使用Maven构建项目方便打包
项目结构
wordcount.java`
package mr;
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.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
public class wordcount {
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
// Job 类是一个单例模式:
Job job = Job.getInstance(conf); // job -> yarn 生成job
//打包为jar去运行
job.setJarByClass(wordcount.class);
// 分别指定Mapper 和Reducer 是哪个类
job.setMapperClass(WordsMapper.class);
job.setReducerClass(WordsReducer.class);
// 制定 Mapper 的输出Key 和 Value的类型
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(LongWritable.class);
// 指定 Reducer的输出Key 和Value 的类型
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);
// 设置输入的文件
Path inputPath = new Path(args[0]);
// 设置输出的路径 : 注意这个路径一定不要存在
Path outputPath = new Path(args[1]);
FileInputFormat.setInputPaths(job,inputPath);
FileOutputFormat.setOutputPath(job,outputPath);
// 执行 true -> console打印信息, false-> 不打印
job.waitForCompletion(true);
}
}
WordsMapper.java
package mr;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import java.io.IOException;
public class WordsMapper extends Mapper<LongWritable,Text,Text,LongWritable> {
@Override
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
String[] strs = value.toString().split(" ");
for(String s : strs) {
context.write(new Text(s),new LongWritable(1));
}
}
}
WordsReducer.java
package mr;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
import java.io.IOException;
class WordsReducer extends Reducer<Text, LongWritable,Text,LongWritable> {
@Override
protected void reduce(Text key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException {
long count = 0; // 用来计算每一个单词所出现的次数
for (LongWritable value : values) {
count = count + value.get();
}
context.write(key, new LongWritable(count));
}
}
使用Maven插件打包
控制台出现BUILD SUCCESS即为打包成功
打包成功后,jar包会出现在target目录下
右键点击 Show in Explorer 打开jar包所在位置
将此jar包通过SFTP工具上传至Hadoop master虚拟机上
1、首先启动hadoop,start-all.sh(必须正常运行)
2、新建hdfs文件夹 input
hdfs dfs -mkdir -p /input
3、上传word.txt文件至 /input 文件夹下
hdfs dfs -put word.txt /input
4、运行wordcount实例
hadoop jar Hadoop-1.0-SNAPSHOT.jar mr.wordcount /input /output
jar包名称根据自己的来,mr.wordcount是 包名.类名