package mr.temp;
import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.DoubleWritable; import org.apache.hadoop.io.LongWritable; 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; import org.apache.hadoop.util.GenericOptionsParser;
import java.io.IOException;
public class TopTemp { static class MyMapper extends Mapper<LongWritable, Text, Text, DoubleWritable> { Text outKey = new Text(); DoubleWritable outValue = new DoubleWritable();
@Override protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { try { String[] datas = value.toString().split("\t"); outValue.set(Double.valueOf(datas[1])); outKey.set(datas[0].substring(0, 10));//按照天进行统计最高气温 context.write(outKey, outValue); outKey.set(datas[0].substring(0, 7));//按照月进行统计最高气温 context.write(outKey, outValue); outKey.set(datas[0].substring(0, 4));//按照年进行统计最高气温 context.write(outKey, outValue); } catch (Exception e) { e.printStackTrace(); } } }
static class MyReducer extends Reducer<Text, DoubleWritable, Text, DoubleWritable> { @Override protected void reduce(Text key, Iterable<DoubleWritable> values, Context context) throws IOException, InterruptedException { double max = 0; for (DoubleWritable value : values) { max = Math.max(max, value.get()); } context.write(key, new DoubleWritable(max)); } }
public static void run(String[] args) throws Exception { Configuration conf = new Configuration(); conf.set("mapred.jar", "D:/IDEAWorks/hadoopAPI/target/hadoopAPI-1.0-SNAPSHOT.jar"); String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs(); if (otherArgs.length != 2) { System.err.println("Usage: TopTemp <in> <out>"); System.exit(2); } Job job = Job.getInstance(conf, "TopTemp"); job.setJarByClass(TopTemp.class); job.setMapperClass(MyMapper.class); job.setReducerClass(MyReducer.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(DoubleWritable.class); FileInputFormat.addInputPath(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); boolean isSuccess = job.waitForCompletion(true); System.exit(isSuccess ? 0 : 1); }
public static void main(String[] args) throws Exception { args = new String[]{"file:///D:/data/weather", "hdfs://n2:9820/remoteUser/r3"}; run(args); } } |