Hadoop的三种模式以及相应的安装细节Google上一大把,其实都基本上是一些参数的设置。
下面自己在.bashrc文件中的设置:
# setting in .bashrc export HADOOP_INSTALL=/home/stephenchan/hadoop-0.20.2 export CLASSPATH=.:$HADOOP_INSTALL/hadoop-0.20.2-core.jar:$HADOOP_INSTALL/lib:$CLASSPATH export PATH=$PATH:$HADOOP_INSTALL/bin
样例的代码是来自<Hadoop : The Definitive Guide>一书,由于没有拿到天气的数据,所以自己用代码生成了一个类似的样例数据,只有年份和温度,用MapReduce来取每年的最高温度,但我省去了日期中的天,保留了年。代码在standalone模式下运行即可,官方的参考文档 : http://hadoop.apache.org/common/docs/r0.20.2/cn/。目前Hadoop只在Linux下完全支持商用运行,在Unix和Windows只支持用来开发。
生成示例数据的Python代码(生成后再手动给三个年份设置最大的temp值(如999)来观察结果的正常与否):
#!/usr/bin/env python import string import random import hashlib random_chars = string.digits year_list = [1990, 2000, 2010] for idx in range(1, 1000): year = year_list[idx%3] temp = random.sample(random_chars, 3) s = "%s %s" % (year, "".join(temp)) print s
MaxTemperature.java的源代码:
/* MaxTemperature.java */
import java.io.IOException;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapreduce.*;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
public class MaxTemperature {
static class MaxTemperatureMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
public void map(LongWritable key, Text value, Context context)
throws IOException, InterruptedException {
String line = value.toString();
// 从每行的数据中分解出年和温度
String year = line.substring(0, 4);
int airTemperature = Integer.parseInt(line.substring(5, 8));
context.write(new Text(year), new IntWritable(airTemperature));
}
}
static class MaxTemperatureReducer extends Reducer<Text, IntWritable, Text, IntWritable> {
public void reduce(Text key, Iterable<IntWritable> values, Context context)
throws IOException, InterruptedException {
int maxValue = Integer.MIN_VALUE;
// key为年份, values为该年每天的温度,求出最大的温度值
for (IntWritable value : values) {
maxValue = Math.max(maxValue, value.get());
}
context.write(key, new IntWritable(maxValue));
}
}
public static void main(String[] args) throws Exception {
if(args.length !=2) {
System.err.println("Usage: MaxTemperature <input path> <output path>");
System.exit(-1);
}
Job job = new Job();
job.setJarByClass(MaxTemperature.class);
FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
job.setMapperClass(MaxTemperatureMapper.class);
job.setReducerClass(MaxTemperatureReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
System.exit(job.waitForCompletion(true)?0:1);
}
}
执行的命令如下,虽然在Hadoop的命令文档中有提供”hadoop CLASSNAME”这样的命令,但我折腾了很久都一直提示”NoClassDefFoundError”,因此只能打包成jar然后再用”hadoop jar”命令运行。
mkdir MaxTemperature javac -d MaxTemperature MaxTemperature.java jar cvf MaxTemperature.jar -C MaxTemperature/ . hadoop jar MaxTemperature.jar MaxTemperature sample.txt output
结果的输出会在output的目录下。