MapReduce2-3.1.1 分布式計(jì)算 實(shí)驗(yàn)示例 (三)二次排序

大家好丧肴,我是Iggi。

今天我給大家分享的是MapReduce2-3.1.1版本的SecondarySort實(shí)驗(yàn)。

關(guān)于MapReduce的一段文字簡(jiǎn)介請(qǐng)自行查閱我的實(shí)驗(yàn)示例:MapReduce2-3.1.1 實(shí)驗(yàn)示例 單詞計(jì)數(shù)(一)

好,下面進(jìn)入正題。介紹Java操作MapReduce2組件完成SecondarySort的操作腻脏。

首先,使用IDE建立Maven工程银锻,建立工程時(shí)沒(méi)有特殊說(shuō)明永品,按照向?qū)崾军c(diǎn)擊完成即可。重要的是在pom.xml文件中添加依賴包击纬,內(nèi)容如下圖:

image.png

待系統(tǒng)下載好依賴的jar包后便可以編寫程序了鼎姐。

展示實(shí)驗(yàn)代碼:

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
    {
        /**
         * 設(shè)定MapReduce示例擁有HDFS的操作權(quán)限
         */
        System.setProperty("HADOOP_USER_NAME", "hdfs"); 
        
        /**
         * 為了清楚的看到輸出結(jié)果,暫將集群調(diào)試信息缺省更振。
         * 如果想查閱集群調(diào)試信息症见,取消注釋即可。
         */
        BasicConfigurator.configure();
        
        /**
         * MapReude實(shí)驗(yàn)準(zhǔn)備階段:
         * 定義HDFS文件路徑
         */
        String defaultFS = "hdfs://master2.linose.cloud.beijing.com:8020";
        String inputPath = defaultFS + "/index.dirs/inputsort.txt";
        String outputPath = defaultFS + "/index.dirs/sort";
        
        /**
         * 生產(chǎn)配置殃饿,并獲取HDFS對(duì)象
         */
        Configuration conf = new Configuration();
        conf.set("fs.defaultFS", defaultFS);
        FileSystem system = FileSystem.get(conf);
        
        /**
         * 定義輸入路徑谋作,輸出路徑
         */
        Path inputHdfsPath = new Path(inputPath);
        Path outputHdfsPath = new Path(outputPath);
        
        /**
         * 如果實(shí)驗(yàn)數(shù)據(jù)文件不存在則創(chuàng)建數(shù)據(jù)文件
         */
        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();
        }
        
        /**
         * 如果實(shí)驗(yàn)結(jié)果目錄存在,遍歷文件內(nèi)容全部刪除
         */
        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);
        }
        
        /**
         * 創(chuàng)建MapReduce任務(wù)并設(shè)定Job名稱
         */
        Job job = Job.getInstance(conf, "Secondary Sort");
        job.setJarByClass(SecondarySort.class);
        
        /**
         * 設(shè)置輸入文件乎芳、輸出文件
         */
        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);
        
        /**
         * 設(shè)定Reduce數(shù)量并執(zhí)行
         */
        job.setNumReduceTasks(1);
        job.waitForCompletion(true);
        
        /**
         * 然后輪詢進(jìn)度,直到作業(yè)完成肴甸。
         */
        float progress = 0.0f;
        do {
            progress = job.setupProgress();
            System.out.println("Secondary Sort: 的當(dāng)前進(jìn)度:" + progress * 100);
            Thread.sleep(1000);
        } while (progress != 1.0f && !job.isComplete());
        
        /**
         * 如果成功寂殉,查看輸出文件內(nèi)容
         */
        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測(cè)試類:

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測(cè)試類:

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());
        }
    }
}

下圖為測(cè)試結(jié)果:


image.png

至此,MapReduce2-3.1.1 Secondary Sort 實(shí)驗(yàn)示例演示完畢原在。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末友扰,一起剝皮案震驚了整個(gè)濱河市彤叉,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌村怪,老刑警劉巖秽浇,帶你破解...
    沈念sama閱讀 217,509評(píng)論 6 504
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異甚负,居然都是意外死亡柬焕,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,806評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門梭域,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)斑举,“玉大人,你說(shuō)我怎么就攤上這事病涨「荤瑁” “怎么了?”我有些...
    開封第一講書人閱讀 163,875評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵没宾,是天一觀的道長(zhǎng)凌彬。 經(jīng)常有香客問(wèn)我沸柔,道長(zhǎng)循衰,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,441評(píng)論 1 293
  • 正文 為了忘掉前任褐澎,我火速辦了婚禮会钝,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘工三。我一直安慰自己迁酸,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,488評(píng)論 6 392
  • 文/花漫 我一把揭開白布俭正。 她就那樣靜靜地躺著奸鬓,像睡著了一般。 火紅的嫁衣襯著肌膚如雪掸读。 梳的紋絲不亂的頭發(fā)上串远,一...
    開封第一講書人閱讀 51,365評(píng)論 1 302
  • 那天,我揣著相機(jī)與錄音儿惫,去河邊找鬼澡罚。 笑死,一個(gè)胖子當(dāng)著我的面吹牛肾请,可吹牛的內(nèi)容都是我干的留搔。 我是一名探鬼主播,決...
    沈念sama閱讀 40,190評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼铛铁,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼隔显!你這毒婦竟也來(lái)了却妨?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,062評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤荣月,失蹤者是張志新(化名)和其女友劉穎管呵,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體哺窄,經(jīng)...
    沈念sama閱讀 45,500評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡捐下,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,706評(píng)論 3 335
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了萌业。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片坷襟。...
    茶點(diǎn)故事閱讀 39,834評(píng)論 1 347
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖生年,靈堂內(nèi)的尸體忽然破棺而出婴程,到底是詐尸還是另有隱情,我是刑警寧澤抱婉,帶...
    沈念sama閱讀 35,559評(píng)論 5 345
  • 正文 年R本政府宣布档叔,位于F島的核電站,受9級(jí)特大地震影響蒸绩,放射性物質(zhì)發(fā)生泄漏衙四。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,167評(píng)論 3 328
  • 文/蒙蒙 一患亿、第九天 我趴在偏房一處隱蔽的房頂上張望传蹈。 院中可真熱鬧,春花似錦步藕、人聲如沸惦界。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,779評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)沾歪。三九已至,卻和暖如春雾消,著一層夾襖步出監(jiān)牢的瞬間灾搏,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,912評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工仪或, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留确镊,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,958評(píng)論 2 370
  • 正文 我出身青樓范删,卻偏偏與公主長(zhǎng)得像蕾域,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,779評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容