MapReduce实现温度排序(六)

1. 任务需求

找出每年每月的3个最高温度时刻并进行降序排列

2. 上传文件

vi weather

一通乱敲:
在这里插入图片描述

hadoop fs -put weather /weather

3. 实例代码

3.1 实现思路

为了提高执行效率,将每一年的数据分别由同的Reduce执行,产生不同的文件。把每年的温度数据通过处理,找到每月最高的三个温度时刻。该实例中设计的类及其功能如下:

类名功能
MyKey对时间和温度进行封装,同时实现序列化和反序列化
MyGroup主要完成分组任务,先比较年,如相等则比较月
MyMapper将数据解析为key-value格式(KeyValueTextInputFormat类的输入格式:key:2018-12-01 23:13:33 value:1)
MyPartitioner控制Reducer的数量,对每一年的数据进行分区
MyReducer将每个月的三个最高温度的记录取出
MySort根据年、月、温度进行排序
RunJob控制整个程序的流程

3.2 源代码

MyKey类:

package com.mapreduce.weater;

import org.apache.hadoop.io.WritableComparable;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

public class MyKey implements WritableComparable {

    private int year;
    private int month;
    private double air;
    //set get 方法
    public int getYear(){return year;}
    public void setYear(int year){this.year = year;}
    public int getMonth(){return month;}
    public void setMonth(int month){this.month = month;}
    public double getAir(){return air;}
    public void setAir(double air){this.air = air;}

    @Override
    public int compareTo(Object o) {
        //按字典序进行比较
        return this == o ? 0:1;
    }

    @Override
    public void write(DataOutput out) throws IOException {
        //通过write方法写入序列化的数据流
        out.writeInt(year);
        out.writeInt(month);
        out.writeDouble(air);
    }

    @Override
    public void readFields(DataInput in) throws IOException {
        //通过该方法从序列化的数据流中读取进行赋值
        year = in.readInt();
        month = in.readInt();
        air = in.readDouble();
    }
}

MyGroup类:

package com.mapreduce.weater;


import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.io.WritableComparator;

import java.text.SimpleDateFormat;
import java.util.Date;

public class MyGroup extends WritableComparator {
    //通过继承WritableComparator类来实现排序
    public MyGroup(){
        super(MyKey.class, true);
    }
    @Override
    public int compare(WritableComparable a, WritableComparable b){
        String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        System.out.println("group执行时间:"+ time);
        MyKey myKey =  (MyKey)a;
        MyKey myKey1 =  (MyKey)b;
        //先比较年,如果年相同则比较月
        int resultYear = Integer.compare(myKey.getYear(), myKey1.getYear());
        if(resultYear == 0){
            return Integer.compare(myKey.getMonth(), myKey1.getMonth());
        }
        return resultYear;
    }
}

MyMapper类:

package com.mapreduce.weater;

import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import java.io.IOException;

public class MyMapper extends Mapper<Text, Text, MyKey, Text> {

    @Override
    protected void map(Text key, Text value, Context context)
    throws IOException, InterruptedException {
        //输入的key:2018-12-01 23:13:33 value 1
        String[] strs = key.toString().split("-");
        //然后将年、月、温度封装到MyKey中
        MyKey myKey = new MyKey();
        myKey.setYear(Integer.parseInt(strs[0])); //年
        myKey.setMonth(Integer.parseInt(strs[1]));//月
        myKey.setAir(Double.parseDouble(value.toString()));//温度
        context.write(myKey, new Text(key.toString()+"\t"+value)); //key为MyKey的实例,value为对应的原始数据
    }
}

MyPartitioner类:

package com.mapreduce.weater;

import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Partitioner;

import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MyPartitioner extends Partitioner<MyKey, Text> {
    @Override
    public int getPartition(MyKey myKey, Text text, int numPartitions) {
        String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        System.out.println("partitioner执行时间:"+ time);
        return (myKey.getYear() - 2015)%numPartitions;
        //2015 0 第一个分区
        //2016 1 第二个分区
        //2017 2 第三个分区
        //2018 3 第四个分区
    }
}

MyReducer类:

package com.mapreduce.weater;

import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;

public class MyReducer extends Reducer<MyKey, Text, NullWritable, Text> {
    @Override
    protected void reduce(MyKey myKey, Iterable<Text> iterables, Context context)
    throws IOException, InterruptedException {
        int sum = 0;
        for(Text iterable:iterables){
            sum++;
            if(sum>3) break;
            else
                context.write(NullWritable.get(), iterable);
        }
    }
}

MySort类:

package com.mapreduce.weater;

import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.io.WritableComparator;

import java.text.SimpleDateFormat;
import java.util.Date;

public class MySort extends WritableComparator {
    //使用super()调用序列化的构造函数
    public MySort(){
        super(MyKey.class, true);
    }
    @Override
    public int compare(WritableComparable a, WritableComparable b){
        String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        System.out.println("sort执行时间:"+ time);

        MyKey myKey = (MyKey)a;
        MyKey myKey1 = (MyKey)b;
        //先比较年
        int resultYear = Integer.compare(myKey.getYear(), myKey1.getYear());
        //再比较月
        if(resultYear == 0) {
            int resultMonth = Integer.compare(myKey.getMonth(), myKey1.getMonth());

            //最后比较温度
            if (resultMonth == 0){
                //月相等就把温度按倒序排列,加-即可。
                return -Double.compare(myKey.getAir(), myKey1.getAir());
            }
            return resultMonth;
        }
        return resultYear;
    }
}

RunJob类:

package com.mapreduce.weater;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.NullWritable;
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.input.KeyValueTextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;

import java.net.URI;

public class RunJob {
    private static final String INPUT_PATH = "hdfs://master002:9000/weather";
    private static final String OUTPUT_PATH = "hdfs://master002:9000/output";

    public static void main(String[] args) throws Exception {
        System.setProperty("HADOOP_USER_NAME", "hadoop");
        Configuration conf = new Configuration();
        //提升代码的健壮性
        final FileSystem fileSystem = FileSystem.get(URI.create(INPUT_PATH), conf);
        if (fileSystem.exists(new Path(OUTPUT_PATH))) {
            fileSystem.delete(new Path(OUTPUT_PATH), true);
        }
        Job job = Job.getInstance(conf, "weather");
        //run jar class 主方法
        job.setJarByClass(RunJob.class);
        //设置map
        job.setMapperClass(MyMapper.class);
        job.setMapOutputKeyClass(MyKey.class);
        job.setMapOutputValueClass(Text.class);
        //设置reduce
        job.setReducerClass(MyReducer.class);
        job.setOutputKeyClass(NullWritable.class);
        job.setOutputValueClass(Text.class);
        //设置partition
        job.setPartitionerClass(MyPartitioner.class);
        job.setNumReduceTasks(4); //reducer的数量
        //设置SortComparatorClass
        job.setSortComparatorClass(MySort.class); //在进入reducer之前进行排序
        //设置GroupingComparatorClass
        job.setGroupingComparatorClass(MyGroup.class);
        //设置input format
        job.setInputFormatClass(KeyValueTextInputFormat.class);
        //键:第一个tab字符之前所有字符,值:剩下的字符
        FileInputFormat.addInputPath(job, new Path(INPUT_PATH));
        //设置output format
        job.setOutputFormatClass(TextOutputFormat.class); //默认输出类型
        FileOutputFormat.setOutputPath(job, new Path(OUTPUT_PATH));
        //提交job
        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }
}

4. 运行效果

在这里插入图片描述
这里我还分别输出了partition、sort、group三个方法的执行时间,得出执行顺序是:partitioner->sort->group。
通过查资料得知:

sort是在分区内根据key进行排序。
group是分组,是在partition里面再分组,相同的key分到一个组中去。

首先给数据分区,将同一个区的数据分配到一个reducer中去;然后利用组sort方法,实现排序;然后。利用group方法,按照某规则将数据分到一个组里面去。

如果出现任何BUG,欢迎下方留言讨论。。。。

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值