hadoop开发应用
一、文件上传
-
创建input文件夹
# hadoop fs -mkdir /input
-
上传文件到input文件夹下
# hadoop fs -put dat0102.dat /input/
二、查询指定字符串出现次数
1. 编写代码
如果忘记了,可以查看:
$HADOOP_HOME/share/doc/hadoop/hadoop-mapreduce-client/hadoop-mapreduce-client-core/MapReduceTutorial.html
代码如下:
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 {
public static class TokenizerMapper
extends Mapper<Object, Text, Text, IntWritable>{
private final static IntWritable one = new IntWritable(1);
private Text word = new Text();
private static String findStr = "";
public void map(Object key, Text value, Context context)
throws IOException, InterruptedException {
Configuration conf=context.getConfiguration();
findStr = conf.get("findStr");
StringTokenizer itr = new StringTokenizer(value.toString());
while (itr.hasMoreTokens()) {
String wordStr = itr.nextToken();
if(!findStr.equals(wordStr)) continue;
word.set(wordStr);
context.write(word, one);
}
}
}
public static class IntSumReducer
extends Reducer<Text,IntWritable,Text,IntWritable> {
private IntWritable result = new IntWritable();
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();
conf.set("findStr", args[2]);
Job job = Job.getInstance(conf, "word count");
job.setJarByClass(WordCount.class);
job.setMapperClass(TokenizerMapper.class);
job.setCombinerClass(IntSumReducer.class);
job.setReducerClass(IntSumReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}
2. 编译代码与打包
# hadoop com.sun.tools.javac.Main WordCount.java
# jar cf wc.jar WordCount*.class
3. 运行与输出存储
# #第一个参数为输入目录,第二个参数为输出目录,第三个参数为需要查找的字符串
# hadoop jar wc.jar WordCount /input/ /output/ Hadoop# hadoop fs -cat /output/part-r-00000
输出结果: Hadoop 986
4. 远程使用windows客户端
添加JVM属性: -DHADOOP_USER_NAME=hadoop (hadoop为hdfs目录权限用户)
程序运行参数: hdfs://192.168.17.128:9000/input/ hdfs://192.168.17.128:9000/output/wc7/ Hadoop