MapReduce 编程不可怕,一篇文章搞定它

MapReduce 编程不可怕,一篇文章搞定它前言本文隶属于专栏《1000个问题搞定大数据技术体系》,该专栏为笔者原创,引用请注明来源,不足和错误之处请在评论区帮忙指出,谢谢!本专栏目录结构和参考文献请见1000个问题搞定大数据技术体系正文需求:WordCount,大数据领域的HelloWorld。Mapperpackagecom.shockang.study.bigdata.mapreduce;importjava.io.IOException;importorg.apache.hadoop.io.IntWr

大家好,又见面了,我是你们的朋友全栈君。

前言

本文隶属于专栏《1000个问题搞定大数据技术体系》,该专栏为笔者原创,引用请注明来源,不足和错误之处请在评论区帮忙指出,谢谢!

本专栏目录结构和参考文献请见1000个问题搞定大数据技术体系

正文

需求: Word Count,大数据领域的 Hello World。

Mapper

package com.shockang.study.bigdata.mapreduce;

import java.io.IOException;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

public class WordCountMapper extends Mapper<LongWritable, Text, Text, IntWritable> { 
   
    protected void map(LongWritable key, Text value, Context context)
            throws IOException, InterruptedException { 
   
        String[] words = value.toString().split(" ");
        for (String word : words) { 
   
            // 每个单词出现1次,作为中间结果输出
            context.write(new Text(word), new IntWritable(1));
        }
    }
}

Reducer

package com.shockang.study.bigdata.mapreduce;

import java.io.IOException;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

public class WordCountReducer extends Reducer<Text, IntWritable, Text, IntWritable> { 
   
    /* key: hello value: List(1, 1, ...) */
    protected void reduce(Text key, Iterable<IntWritable> values,
                          Context context) throws IOException, InterruptedException { 
   
        int sum = 0;

        for (IntWritable count : values) { 
   
            sum = sum + count.get();
        }
        context.write(key, new IntWritable(sum));
    };
}

Main

package com.shockang.study.bigdata.mapreduce;

import java.io.IOException;

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

public class WordCountMain { 
   
    public static void main(String[] args) throws IOException,
            ClassNotFoundException, InterruptedException { 
   
        if (args.length != 2) { 
   
            System.out.println("please input Path!");
            System.exit(0);
        }

        Configuration configuration = new Configuration();
        Job job = Job.getInstance(configuration, WordCountMain.class.getSimpleName());

        // 打jar包
        job.setJarByClass(WordCountMain.class);

        // 通过job设置输入/输出格式,默认的就是 TextInputFormat/TextOutputFormat
        job.setInputFormatClass(TextInputFormat.class);
        job.setOutputFormatClass(TextOutputFormat.class);

        // 设置输入/输出路径
        FileInputFormat.setInputPaths(job, new Path(args[0]));
        FileOutputFormat.setOutputPath(job, new Path(args[1]));

        // 设置处理Map/Reduce阶段的类
        job.setMapperClass(WordCountMapper.class);
        job.setReducerClass(WordCountReducer.class);
        //如果map、reduce的输出的kv对类型一致,直接设置reduce的输出的kv对就行
        //如果不一样,需要分别设置map, reduce的输出的kv类型
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(IntWritable.class);
        // 设置最终输出key/value的类型
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);

        // 提交作业
        job.waitForCompletion(true);

    }

}

Combiner

package com.shockang.study.bigdata.mapreduce;


import java.io.IOException;

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


public class WordCountMainWithCombiner { 
   
    public static void main(String[] args) throws IOException,
            ClassNotFoundException, InterruptedException { 
   
        if (args.length != 2) { 
   
            System.out.println("please input Path!");
            System.exit(0);
        }

        Configuration configuration = new Configuration();
        Job job = Job.getInstance(configuration, WordCountMainWithCombiner.class.getSimpleName());

        // 打jar包
        job.setJarByClass(WordCountMainWithCombiner.class);

        // 通过job设置输入/输出格式
        job.setInputFormatClass(TextInputFormat.class);
        job.setOutputFormatClass(TextOutputFormat.class);

        // 设置输入/输出路径
        FileInputFormat.setInputPaths(job, new Path(args[0]));
        FileOutputFormat.setOutputPath(job, new Path(args[1]));

        // 设置处理Map/Reduce阶段的类
        job.setMapperClass(WordCountMapper.class);
        job.setCombinerClass(WordCountReducer.class);
        job.setReducerClass(WordCountReducer.class);
        //如果map、reduce的输出的kv对类型一致,直接设置reduce的输出的kv对就行
        // 如果不一样,需要分别设置map, reduce的输出的kv类型
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(IntWritable.class);
        // 设置最终输出key/value的类型m
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);

        // 提交作业
        job.waitForCompletion(true);

    }
}

二次排序

package com.shockang.study.bigdata.mapreduce;

import org.apache.hadoop.io.WritableComparable;

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

/** * 现有需求,需要自定义key类型,并自定义key的排序规则,如按照人的salary降序排序,若相同,则再按age升序排序 */
public class Person implements WritableComparable<Person> { 
   
    private String name;
    private int age;
    private int salary;

    public Person() { 
   
    }

    public Person(String name, int age, int salary) { 
   
        this.name = name;
        this.age = age;
        this.salary = salary;
    }

    public String getName() { 
   
        return name;
    }

    public void setName(String name) { 
   
        this.name = name;
    }

    public int getAge() { 
   
        return age;
    }

    public void setAge(int age) { 
   
        this.age = age;
    }

    public int getSalary() { 
   
        return salary;
    }

    public void setSalary(int salary) { 
   
        this.salary = salary;
    }

    @Override
    public String toString() { 
   
        return this.salary + " " + this.age + " " + this.name;
    }

    public int compareTo(Person o) { 
   
        //先比较salary,高的排序在前;若相同,age小的在前
        int compareResult1 = this.salary - o.salary;
        if (compareResult1 != 0) { 
   
            return -compareResult1;
        } else { 
   
            return this.age - o.age;
        }
    }

    public void write(DataOutput dataOutput) throws IOException { 
   
        //序列化,将NewKey转化成使用流传输的二进制
        dataOutput.writeUTF(name);
        dataOutput.writeInt(age);
        dataOutput.writeInt(salary);
    }

    public void readFields(DataInput dataInput) throws IOException { 
   
        //使用in读字段的顺序,要与write方法中写的顺序保持一致
        this.name = dataInput.readUTF();
        this.age = dataInput.readInt();
        this.salary = dataInput.readInt();
    }
}

自定义分区

package com.shockang.study.bigdata.mapreduce;

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

import java.util.HashMap;

public class CustomPartitioner extends Partitioner<Text, IntWritable> { 
   
    public static HashMap<String, Integer> dict = new HashMap<>();

    static { 
   
        dict.put("Dear", 0);
        dict.put("Bear", 1);
        dict.put("River", 2);
        dict.put("Car", 3);
    }

    public int getPartition(Text text, IntWritable intWritable, int i) { 
   
        return dict.get(text.toString());
    }
}

数据倾斜处理

当遇到数据倾斜的时候,我们可以在 Reducer 中日志记录哪些超过阈值的 key

package com.shockang.study.bigdata.mapreduce;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;
import java.util.Iterator;

public class WordCountReducerWithDataSkew extends Reducer<Text, IntWritable, Text, IntWritable> { 
   

    public static final String MAX_VALUES = "skew.maxvalues";
    private int maxValueThreshold;

    @Override
    protected void setup(Context context) throws IOException, InterruptedException { 
   
        Configuration conf = context.getConfiguration();
        maxValueThreshold = Integer.parseInt(conf.get(MAX_VALUES));
    }

    /* key: hello value: List(1, 1, ...) */
    protected void reduce(Text key, Iterable<IntWritable> values,
                          Context context) throws IOException, InterruptedException { 
   
        int i = 0;
        for (IntWritable value : values) { 
   
            System.out.println(value);
            i++;
        }

        if (++i > maxValueThreshold) { 
   
            System.out.println("Received " + i + " values for key " + key);
        }
    }
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/147546.html原文链接:https://javaforall.net

(0)
上一篇 2022年6月14日 下午10:36
下一篇 2022年6月14日 下午10:36


相关推荐

  • 提取pfx证书密钥对

    提取pfx证书密钥对两个测试证书test.pfx和test.cer.其中pfx证书包含RSA的公钥和密钥;cer证书用于提取pfx证书中密钥时允许当前电脑进行合法操作提取步骤如下:点击test.cer,安装cer证书2.从pfx提取密钥信息,并转换为key格式(pfx使用pkcs12模式补足)(1)提取密钥对opensslpkcs12-intest.pfx-nocerts-nodes-outtest.key//如果pfx证书已加密,会提示输入密码。如果cer证书没有安装

    2022年5月31日
    60
  • Python搭建代理IP池(一)- 获取 IP[通俗易懂]

    Python搭建代理IP池(一)- 获取 IP[通俗易懂]使用爬虫时,大部分网站都有一定的反爬措施,有些网站会限制每个IP的访问速度或访问次数,超出了它的限制你的IP就会被封掉。对于访问速度的处理比较简单,只要间隔一段时间爬取一次就行了,避免频繁访问;而对于访问次数,就需要使用代理IP来帮忙了,使用多个代理IP轮换着去访问目标网址可以有效地解决问题。目前网上有很多的代理服务网站可以提供代理服务,也提供一些免费的代理,但可用性较差,如果需…

    2022年6月5日
    134
  • 电压转电流电路

    电压转电流电路图1 电压转电流原理图   如图 1是输入输出无偏置型电压转电流信号调理的典型电路。其中运放A、电阻R13、三极管Q10构成压控电流源电路;电阻R9、R11、运放B、三极管Q8、Q9构成电流放大电路。   当电压信号加在运放A同向输入时,由运放特性:虚短、虚断可知反向输入端电压跟随同向输入端电压信号,此时在电阻R13支路上产生电流流过三极管Q10,三极管Q10基极受运放A输出端

    2022年6月2日
    40
  • servlet-EL表达式与JSTL标签「建议收藏」

    servlet-EL表达式与JSTL标签「建议收藏」EL表达式EL表达式的作用:EL表达式主要是代替jsp页面中的表达式脚本在jsp页面中进行数据输出。因为EL表达式在输出数据的时候,要比jsp表达式脚本要简洁的多格式$(表达式)<%@ page import=”java.util.Map” %><%@ page import=”java.util.HashMap” %><%@ page contentType=”text/html;charset=UTF-8″ language=”java” %><h

    2022年8月8日
    8
  • linux安装python虚拟环境_windows安装python虚拟环境

    linux安装python虚拟环境_windows安装python虚拟环境准备1、使用wget命令下载安装包,耐心等待下载。安装步骤1、安装gcc2、安装readline3、把tgz文件进行解压4、切换到python目录5、解决PIP包管理器所需依赖包。6、安装文件7、开始编译安装,自定义安装目录。8、修改系统内置Python软链接。9、针对Centos系统的一些问题Centos的包资源管理器是yum,由于该管理器是由Python语言实现的,故依赖于系统安装Python…

    2022年8月28日
    8
  • 什么时候PHP经验MySQL存储过程

    什么时候PHP经验MySQL存储过程

    2022年1月4日
    56

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号