MapReduce2-3.1.1 分布式计算 实验示例 (三)二次排序

大家好,我是Iggi。

今天我给大家分享的是MapReduce2-3.1.1版本的SecondarySort实验。

关于MapReduce的一段文字简介请自行查阅我的实验示例:MapReduce2-3.1.1 实验示例 单词计数(一)

好,下面进入正题。介绍Java操作MapReduce2组件完成SecondarySort的操作。

首先,使用IDE建立Maven工程,建立工程时没有特殊说明,按照向导提示点击完成即可。重要的是在pom.xml文件中添加依赖包,内容如下图:

image.png

待系统下载好依赖的jar包后便可以编写程序了。

展示实验代码:

package linose.mapreduce.secondarysort;

import java.io.IOException;
import java.io.OutputStreamWriter;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.LocatedFileStatus;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.RemoteIterator;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.log4j.BasicConfigurator;

import linose.mapreduce.secondarysort.SecondarySort.FirstPartitioner;
import linose.mapreduce.secondarysort.SecondarySort.KeyComparator;
import linose.mapreduce.secondarysort.SecondarySort.SortMapper;
import linose.mapreduce.secondarysort.SecondarySort.SortReduce;

public class AppSort 
{

    public static void main( String[] args ) throws IOException, ClassNotFoundException, InterruptedException
    {
        /**
         * 设定MapReduce示例拥有HDFS的操作权限
         */
        System.setProperty("HADOOP_USER_NAME", "hdfs"); 
        
        /**
         * 为了清楚的看到输出结果,暂将集群调试信息缺省。
         * 如果想查阅集群调试信息,取消注释即可。
         */
        BasicConfigurator.configure();
        
        /**
         * MapReude实验准备阶段:
         * 定义HDFS文件路径
         */
        String defaultFS = "hdfs://master2.linose.cloud.beijing.com:8020";
        String inputPath = defaultFS + "/index.dirs/inputsort.txt";
        String outputPath = defaultFS + "/index.dirs/sort";
        
        /**
         * 生产配置,并获取HDFS对象
         */
        Configuration conf = new Configuration();
        conf.set("fs.defaultFS", defaultFS);
        FileSystem system = FileSystem.get(conf);
        
        /**
         * 定义输入路径,输出路径
         */
        Path inputHdfsPath = new Path(inputPath);
        Path outputHdfsPath = new Path(outputPath);
        
        /**
         * 如果实验数据文件不存在则创建数据文件
         */
        system.delete(inputHdfsPath, false);
        if (!system.exists(inputHdfsPath)) {
            FSDataOutputStream outputStream = system.create(inputHdfsPath);
            OutputStreamWriter file = new OutputStreamWriter(outputStream);
            file.write("5\t35\tlee\n");
            file.write("11\t21\tAndy\n");
            file.write("8\t25\tDa\n");
            file.write("4\t23\tCoCo\n");
            file.write("9\t21\tAnn\n");
            file.write("2\t34\tchap\n");
            file.write("10\t45\tYee\n");
            file.write("6\t25\tViVi\n");
            file.write("1\t33\tIggi\n");
            file.write("3\t27\ttony\n");
            file.write("7\t29\tsummer\n");
            file.close();
            outputStream.close();
        }
        
        /**
         * 如果实验结果目录存在,遍历文件内容全部删除
         */
        if (system.exists(outputHdfsPath)) {
            RemoteIterator<LocatedFileStatus> fsIterator = system.listFiles(outputHdfsPath, true);
            LocatedFileStatus fileStatus;
            while (fsIterator.hasNext()) {
                fileStatus = fsIterator.next();
                system.delete(fileStatus.getPath(), false);
            }
            system.delete(outputHdfsPath, false);
        }
        
        /**
         * 创建MapReduce任务并设定Job名称
         */
        Job job = Job.getInstance(conf, "Secondary Sort");
        job.setJarByClass(SecondarySort.class);
        
        /**
         * 设置输入文件、输出文件
         */
        FileInputFormat.addInputPath(job, inputHdfsPath);
        FileOutputFormat.setOutputPath(job, outputHdfsPath);
        
        /**
         * 指定Reduce类输出类型Key类型与Value类型
         */
        job.setOutputKeyClass(IntPair.class);
        job.setOutputValueClass(NullWritable.class);
        
        /**
         * 指定自定义Map类,Reduce类,Partitioner类、SortComparator类。
         */
        job.setMapperClass(SortMapper.class);
        job.setReducerClass(SortReduce.class);
        job.setPartitionerClass(FirstPartitioner.class);
        job.setSortComparatorClass(KeyComparator.class);
        
        /**
         * 设定Reduce数量并执行
         */
        job.setNumReduceTasks(1);
        job.waitForCompletion(true);
        
        /**
         * 然后轮询进度,直到作业完成。
         */
        float progress = 0.0f;
        do {
            progress = job.setupProgress();
            System.out.println("Secondary Sort: 的当前进度:" + progress * 100);
            Thread.sleep(1000);
        } while (progress != 1.0f && !job.isComplete());
        
        /**
         * 如果成功,查看输出文件内容
         */
        if (job.isSuccessful()) {
            RemoteIterator<LocatedFileStatus> fsIterator = system.listFiles(outputHdfsPath, true);
            LocatedFileStatus fileStatus;
            while (fsIterator.hasNext()) {
                fileStatus = fsIterator.next();
                FSDataInputStream outputStream = system.open(fileStatus.getPath());
                IOUtils.copyBytes(outputStream, System.out, conf, false);
                outputStream.close();
                System.out.println("--------------------------------------------");
            }
        }
    }
}

展示MapReduce2-3.1.1组件编写IntPair测试类:

package linose.mapreduce.secondarysort;

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

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

public class IntPair implements WritableComparable<IntPair>{

    private IntWritable first;
    private IntWritable second;
    
    public void set(IntWritable first, IntWritable second) {
        this.first = first;
        this.second = second;
    }
    
    public IntPair() {
        set(new IntWritable(), new IntWritable());
    }
    
    public IntPair(int first, int second) {
        set(new IntWritable(first), new IntWritable(second));
    }
    
    public void setFirst(IntWritable first) {
        this.first = first;
    }
    
    public IntWritable getFirst() {
        return first;
    }
    
    public void setSecond(IntWritable second) {
        this.second = second;
    }
    
    public IntWritable getSecond() {
        return second;
    }
    
    public void readFields(DataInput in) throws IOException {
        first.readFields(in);
        second.readFields(in);
    }

    public void write(DataOutput out) throws IOException {
        first.write(out);
        second.write(out);
    }

    public int compareTo(IntPair o) {
        int compare = first.compareTo(o.first);
        if (0 != compare) {
            return compare;
        }
        return second.compareTo(o.second);
    }
    
    public int hashCode() {
        return first.hashCode()*163+second.hashCode();
    }
    
    public boolean equals(Object o) {
        if (o instanceof IntPair) {
            IntPair pair = (IntPair)o;
            return first.equals(pair.first) && second.equals(pair.second);
        }
        return false;
    }

    public String toString() {
        return first + "\t" + second;
    }
}

展示MapReduce2-3.1.1组件编写Secondary Sort测试类:

package linose.mapreduce.secondarysort;

import java.io.IOException;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.io.WritableComparator;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Partitioner;
import org.apache.hadoop.mapreduce.Reducer;

public class SecondarySort {

    public static class SortMapper extends Mapper<LongWritable, Text, IntPair, NullWritable> {
        
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String[] fields = value.toString().split("\t");
            int field1 = Integer.parseInt(fields[0]);
            int field2 = Integer.parseInt(fields[1]);
            context.write(new IntPair(field1, field2), NullWritable.get());
        }
    }
    
    public static class SortReduce extends Reducer<IntPair, NullWritable, IntPair, NullWritable> {
        
        protected void reduce(IntPair key, Iterable<NullWritable> values, Context context) throws IOException, InterruptedException {
            context.write(key, NullWritable.get());
        }
    }
    
    public static class FirstPartitioner extends Partitioner<IntPair, NullWritable> {
        
        public int getPartition(IntPair key, NullWritable value, int partitions) {
            return Math.abs(key.getFirst().get()) % partitions;
        }
    }
    
    public static class KeyComparator extends WritableComparator {
        
        protected KeyComparator() {
            super(IntPair.class, true);
        }
        
        public int compare(@SuppressWarnings("rawtypes") WritableComparable value1, @SuppressWarnings("rawtypes") WritableComparable value2) {
            IntPair pair1 = (IntPair)value1;
            IntPair pair2 = (IntPair)value2;
            
            int compare = pair1.getFirst().compareTo(pair2.getFirst());
            if (0 != compare) {
                return compare;
            }
            
            return -pair1.getSecond().compareTo(pair2.getSecond());
        }
    }
}

下图为测试结果:


image.png

至此,MapReduce2-3.1.1 Secondary Sort 实验示例演示完毕。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 221,576评论 6 515
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,515评论 3 399
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 168,017评论 0 360
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,626评论 1 296
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,625评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,255评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,825评论 3 421
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,729评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,271评论 1 320
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,363评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,498评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,183评论 5 350
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,867评论 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,338评论 0 24
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,458评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,906评论 3 376
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,507评论 2 359

推荐阅读更多精彩内容