大数据开发-Hadoop之MapReduce

news2025/3/11 8:59:02

文章目录

    • MapReduce原理剖析
      • MapReduce之Map阶段
      • MapReduce之Reduce阶段
      • WordCount分析
      • 多文件WordCount分析
    • 实战wordCount案例开发

MapReduce原理剖析

  • MapReduce是一种分布式计算模型,主要用于搜索领域,解决海量数据的计算问题
  • MapReduce由两个阶段组成:Map和Reduce

v2-4ab30eab0c56c4cda575bc6780983c75_720w

MapReduce之Map阶段

  • 框架会把输入的文件夹划分为多个inputSplit,默认每个HDFS的block对应一个inputSplit。通过RecordReader类,把每个inputSplit解析程一个个<k,v>。默认每一行数据,会被解析程一个<k,v>
#比如有个文件
hello world
hello map
input split

# 第一步拆分
<0, hello world>
<12, hello map> #这里的12代表上一行的长度,也就是偏移量
<21, input split>

  • 框架调用Mapper类中的map(…)函数,map函数的输入是<k1,v1>,输出是<k2,v2>,一个inputSplit对应一个Map Task
# 第二步数据会变成如下
<hello, 1>
<world, 1>

<hello, 1>
<map, 1>

<input, 1>
<split, 1>
  • 框架对map输出的<k2,v2>进行分区,不同分区中的<k2,v2>由不同的Reduce Task处理,默认只有1个分区

  • 框架对每个分区中的数据按照k2进行排序分组。分组值的是相同的k2的v2分成一个组

# 排序
<hello, 1>
<hello, 1>
<world, 1>
<map, 1>
<input, 1>
<split, 1>

# 分组
<hello, {1,1}>
<world, {1}>
<map, {1}>
<input, {1}>
<split, {1}>
  • 在Map阶段,框架可以执行Combiner操作-可选

  • 框架会把Map Task输出的<k2,v2>写入Linux的磁盘文件

至此,Map阶段执行结束

MapReduce之Reduce阶段

  • 框架对多个Map Task的输出,按照不同的分区,通过网络Copy到不同的Reduce节点,这个过程称为Shuffle
  • 框架对Reduce节点接收到的相同分区的<k2,v2>进行合并,排序,分组
  • 框架调用Reduce类中的reduce方法,输入<k2,{v2…}>,输出<k3,v3>.一个<k2,{v2…}>调用一次reduce函数
<hello, 2>
<world, 1>
<map, 1>
<input, 1>
<split, 1>
  • 框架将计算结果保存到HDFS中
hello 2
world 1
...

WordCount分析

1532797068747d8a77620a6

多文件WordCount分析

dadc900df3f728105ab114fc74c5b6ab

实战wordCount案例开发

  • 开发Map阶段代码
  • 开发Reduce阶段代码
  • 组装job
/**
 * 读取hdfs的hello.txt中每个单词出现的次数
 *
 * 原始文件的内容
 * hello world
 * hello map
 * input split
 *
 * 最终输出
 *
 * hello 2
 * world 1
 * split 1
 * map 1
 * input 1
 */
public class WordCountJob {


    /**
     * map阶段
     */
    public static class MyMapProcess extends Mapper<LongWritable, Text, Text, LongWritable> {
        /**
         * 实现map函数
         * @param k1
         * @param v1
         * @param context
         * @throws IOException
         * @throws InterruptedException
         */
        @Override
        protected void map(LongWritable k1, Text v1, Context context) throws IOException, InterruptedException {
            // k1代表每行数据的行首偏移量 v1代表每行的内容
            // 对获取的数据每一行切割
            String[] words = v1.toString().split(" ");
            for (String word: words
                 ) {
                // 封装为<k2,v2>的形式
                Text k2 = new Text(word);
                LongWritable v2 = new LongWritable(1L);
                context.write(k2, v2);
            }
        }
    }

    /**
     * reduce阶段
     * 针对<k2,{v2...}>这样的数据进行累加求和,转换为<k3,v3></>
     */
    public static class MyReducer extends Reducer<Text, LongWritable, Text, LongWritable> {

        @Override
        protected void reduce(Text k2, Iterable<LongWritable> v2s, Context context) throws IOException, InterruptedException {
            long sum = 0L;
            for (LongWritable v2: v2s
                 ) {
                sum += v2.get();
            }
            context.write(k2, new LongWritable(sum));
        }
    }

    /**
     * 组装job=map+reduce
     */
    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
        if (args.length < 2) {
            System.out.println("请输入两个目录地址");
             return;
        }
        Configuration entries = new Configuration();
        Job job = Job.getInstance(entries);
        // 必须设置
        job.setJarByClass(WordCountJob.class);
        // 指定输入路径,可以是文件也可以是目录
        FileInputFormat.setInputPaths(job, new Path("args[0]"));

        // 只能指定一个不存在的目录
        FileOutputFormat.setOutputPath(job, new Path("args[1]"));

        // 指定map
        job.setMapperClass(MyMapProcess.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(LongWritable.class);

        // reduce指定
        job.setReducerClass(MyReducer.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(LongWritable.class);

        // 提交job
        job.waitForCompletion(true);
    }
}

  • 打包代码并上传至服务器
mvn clean package -D skipTests

image-20240306163206900

  • 创建测试文件
[root@hadoop01 hadoop-3.2.0]# hdfs dfs -mkdir /test
[root@hadoop01 hadoop-3.2.0]# hdfs dfs -put hello.txt /test
You have new mail in /var/spool/mail/root
[root@hadoop01 hadoop-3.2.0]# hdfs dfs -ls /test
Found 1 items
-rw-r--r--   2 root supergroup         34 2024-03-06 16:29 /test/hello.txt

  • 上传jar包到集群并运行
# 运行相关代码
[root@hadoop01 hadoop-3.2.0]# bin/hadoop jar demo-0.0.1-SNAPSHOT-jar-with-dependencies.jar com.example.hadoop.demo.mapreduce.WordCountJob /test/hello.txt /out
2024-03-06 16:40:27,922 INFO client.RMProxy: Connecting to ResourceManager at hadoop01/192.168.52.100:8032
2024-03-06 16:40:28,962 WARN mapreduce.JobResourceUploader: Hadoop command-line option parsing not performed. Implement the Tool interface and execute your application with ToolRunner to remedy this.
2024-03-06 16:40:29,005 INFO mapreduce.JobResourceUploader: Disabling Erasure Coding for path: /tmp/hadoop-yarn/staging/root/.staging/job_1709626488940_0001
2024-03-06 16:40:29,749 INFO input.FileInputFormat: Total input files to process : 1
2024-03-06 16:40:29,943 INFO mapreduce.JobSubmitter: number of splits:1
2024-03-06 16:40:30,036 INFO Configuration.deprecation: yarn.resourcemanager.system-metrics-publisher.enabled is deprecated. Instead, use yarn.system-metrics-publisher.enabled
2024-03-06 16:40:30,328 INFO mapreduce.JobSubmitter: Submitting tokens for job: job_1709626488940_0001
2024-03-06 16:40:30,329 INFO mapreduce.JobSubmitter: Executing with tokens: []
2024-03-06 16:40:30,588 INFO conf.Configuration: resource-types.xml not found
2024-03-06 16:40:30,588 INFO resource.ResourceUtils: Unable to find 'resource-types.xml'.
2024-03-06 16:40:31,089 INFO impl.YarnClientImpl: Submitted application application_1709626488940_0001
2024-03-06 16:40:31,147 INFO mapreduce.Job: The url to track the job: http://hadoop01:8088/proxy/application_1709626488940_0001/
2024-03-06 16:40:31,147 INFO mapreduce.Job: Running job: job_1709626488940_0001
2024-03-06 16:40:43,417 INFO mapreduce.Job: Job job_1709626488940_0001 running in uber mode : false
2024-03-06 16:40:43,419 INFO mapreduce.Job:  map 0% reduce 0%
2024-03-06 16:40:50,638 INFO mapreduce.Job:  map 100% reduce 0%
2024-03-06 16:40:57,779 INFO mapreduce.Job:  map 100% reduce 100%
2024-03-06 16:40:57,824 INFO mapreduce.Job: Job job_1709626488940_0001 completed successfully
2024-03-06 16:40:57,948 INFO mapreduce.Job: Counters: 54
	File System Counters
		FILE: Number of bytes read=100
		FILE: Number of bytes written=442629
		FILE: Number of read operations=0
		FILE: Number of large read operations=0
		FILE: Number of write operations=0
		HDFS: Number of bytes read=134
		HDFS: Number of bytes written=38
		HDFS: Number of read operations=8
		HDFS: Number of large read operations=0
		HDFS: Number of write operations=2
		HDFS: Number of bytes read erasure-coded=0
	Job Counters 
		Launched map tasks=1
		Launched reduce tasks=1
		Data-local map tasks=1
		Total time spent by all maps in occupied slots (ms)=5635
		Total time spent by all reduces in occupied slots (ms)=4035
		Total time spent by all map tasks (ms)=5635
		Total time spent by all reduce tasks (ms)=4035
		Total vcore-milliseconds taken by all map tasks=5635
		Total vcore-milliseconds taken by all reduce tasks=4035
		Total megabyte-milliseconds taken by all map tasks=5770240
		Total megabyte-milliseconds taken by all reduce tasks=4131840
	Map-Reduce Framework
		Map input records=3
		Map output records=6
		Map output bytes=82
		Map output materialized bytes=100
		Input split bytes=100
		Combine input records=0
		Combine output records=0
		Reduce input groups=5
		Reduce shuffle bytes=100
		Reduce input records=6
		Reduce output records=5
		Spilled Records=12
		Shuffled Maps =1
		Failed Shuffles=0
		Merged Map outputs=1
		GC time elapsed (ms)=159
		CPU time spent (ms)=1880
		Physical memory (bytes) snapshot=306229248
		Virtual memory (bytes) snapshot=5044473856
		Total committed heap usage (bytes)=141049856
		Peak Map Physical memory (bytes)=201551872
		Peak Map Virtual memory (bytes)=2517729280
		Peak Reduce Physical memory (bytes)=104677376
		Peak Reduce Virtual memory (bytes)=2526744576
	Shuffle Errors
		BAD_ID=0
		CONNECTION=0
		IO_ERROR=0
		WRONG_LENGTH=0
		WRONG_MAP=0
		WRONG_REDUCE=0
	File Input Format Counters 
		Bytes Read=34
	File Output Format Counters 
		Bytes Written=38
You have new mail in /var/spool/mail/root

# 查看是否有输出
[root@hadoop01 hadoop-3.2.0]# hdfs dfs -ls /out
Found 2 items
-rw-r--r--   2 root supergroup          0 2024-03-06 16:40 /out/_SUCCESS
-rw-r--r--   2 root supergroup         38 2024-03-06 16:40 /out/part-r-00000
You have new mail in /var/spool/mail/root

# 查看文件内容
[root@hadoop01 hadoop-3.2.0]# hdfs dfs -cat /out/part-r-00000
hello	2
input	1
map	1
split	1
world	1

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1495508.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

热红外图像直方图修正显示

热红外图像的直方图修正是一种用于增强图像对比度和可视化细节的技术。下面是一个使用Python和OpenCV库实现直方图均衡化的示例代码&#xff1a; import cv2 import numpy as np# 读取热红外图像 image cv2.imread(thermal_image.png, cv2.IMREAD_GRAYSCALE)# 对图像进行直方…

植被生长动态与多时间尺度干旱事件的关联性研究

随着全球气候变暖的趋势愈发明显&#xff0c;干旱事件不仅发生的频率增加&#xff0c;其持续时间和影响范围也在不断扩大。干旱对生态环境造成了严重破坏&#xff0c;导致生物多样性减少、土地退化和水资源短缺&#xff1b;对农业生产而言&#xff0c;干旱会导致作物减产甚至绝…

Java精品项目--第5期基于SpringBoot的高速收费系统的设计分析与实现

项目使用技术栈 SpringBootMavenShiroMySQLMybatis-PlusJavaJDK1.8HTML 系统介绍 项目截图

【详识C语言】程序环境和预处理

本章重点&#xff1a; 程序的翻译环境 程序的执行环境 详解&#xff1a;C语言程序的编译链接 预定义符号介绍 预处理指令 #define 宏和函数的对比 预处理操作符#和##的介绍 命令定义 预处理指令 #include 预处理指令 #undef 条件编译 程序的翻译环境和执行环境 在ANSI C的任何…

2024.3.6每日一题

LeetCode 找出数组中的 K -or 值 题目链接&#xff1a;2917. 找出数组中的 K-or 值 - 力扣&#xff08;LeetCode&#xff09; 题目描述 给你一个下标从 0 开始的整数数组 nums 和一个整数 k 。 nums 中的 K-or 是一个满足以下条件的非负整数&#xff1a; 只有在 nums 中&…

Jenkins-Android源码编译【架构设计】(适用鸿蒙/自动化/多产品/持续迭代)

文章目录 Jenkins-Android源码编译【架构设计】&#xff08;适用鸿蒙/自动化/多产品/持续迭代&#xff09;通俗介绍Jenkins框架设计Jenkins部署系统/插件配置JOB配置 源码编译环境准备AOSP编译基本框架编译脚本aosp_build_sciptsjenkins_build_sciptsStage1Stage2Stage3Stage4P…

灵魂指针,教给(一)

欢迎来到白刘的领域 Miracle_86.-CSDN博客 系列专栏 C语言知识 先赞后看&#xff0c;已成习惯 创作不易&#xff0c;多多支持&#xff01; 一、内存和地址 1.1 内存 在介绍知识之前&#xff0c;先来想一个生活中的小栗子&#xff1a; 假如把你放在一个有100间屋子的酒店…

上海亚商投顾:沪指震荡微涨 AI手机、军工板块集体走强

上海亚商投顾前言&#xff1a;无惧大盘涨跌&#xff0c;解密龙虎榜资金&#xff0c;跟踪一线游资和机构资金动向&#xff0c;识别短期热点和强势个股。 一.市场情绪 沪指昨日低开后震荡回升&#xff0c;黄白二线分化明显&#xff0c;银行等权重板块走势较强。AI手机概念股持续…

pytorch_retinaface训练Resnet50_Final.pth过程+无图版安装Nvidia+CUDA驱动GPU

背景 当前处于人脸检测分支&#xff0c;项目就是retinaface官方的代码加上数据集目录结构&#xff0c;目的是训练出最后的模型文件Resnet50_Final.pth 代码 https://gitee.com/congminglst/pytorch_-retinaface.git 项目结构与设计 图片数据集采用widerface&#xff0c; 前…

STM32CubeIDE基础学习-STM32CubeIDE软件快捷键介绍

STM32CubeIDE基础学习-STM32CubeIDE软件快捷键介绍 文章目录 STM32CubeIDE基础学习-STM32CubeIDE软件快捷键介绍前言第1章 查看快捷键方法第2章 设置快捷键方法第3章 常用快捷键示例总结 前言 这个STM32CubeIDE软件使用的是Eclipse框架的开发环境&#xff0c;所以所使用的快捷…

AntV L7初体验

本案例使用L7库和Mapbox GL JS创建的简单地图可视化示例&#xff0c;加载点数据。 文章目录 1. 引入 CDN 链接2. 导出模块3. 创建地图3.1. 注册 token3.2. 创建地图实例 4. 创建场景5.创建点图层6. 演示效果7. 代码实现 1. 引入 CDN 链接 <!-- 1.引入CDN链接 --> <!--…

泰迪智能科技-2024年高校大数据人才培养探索模式

随着数字经济的高速发展&#xff0c;对于大数据人才的需求日益增长。产业数字化和数字产业化之间的关系&#xff0c;已经成为推动社会发展的关键。为此&#xff0c;高校及产业界需要紧密配合&#xff0c;以培养出符合时代需求的大数据人才。 数字产业化与产业数字化高速发…

HarmonyOS NEXT应用开发案例集

概述 随着应用代码的复杂度提升&#xff0c;为了使应用有更好的可维护性和可扩展性&#xff0c;良好的应用架构设计变得尤为重要。本篇文章将介绍一个应用通用架构的设计思路&#xff0c;以减少模块间的耦合、提升团队开发效率&#xff0c;为开发者呈现一个清晰且结构化的开发…

windows11配置电脑IP

windows11配置电脑IP 选择"开始>设置>“网络&Internet >以太网”。在 "属性"下&#xff0c;编辑IP地址&#xff0c;子网掩码&#xff0c;网关以及DNS。

Qt ini配置文件

ini文件用于保存用户的设置操作&#xff0c;下列以背景颜色设置为例子 暂时默认设置为白色背景 这段代码放置在主窗口的构造函数中&#xff0c;用于初始化读取ini文件 QString color;QSettings *set new QSettings("color.ini",QSettings::IniFormat);set->begi…

《探索虚拟与现实的边界:VR与AR谁更能引领未来?》

引言 在当今数字时代&#xff0c;虚拟现实&#xff08;VR&#xff09;和增强现实&#xff08;AR&#xff09;技术正以惊人的速度发展&#xff0c;并逐渐渗透到我们的日常生活中。它们正在重新定义人与技术、人与环境之间的关系&#xff0c;同时也为各行各业带来了全新的可能性。…

学术论文GPT的源码解读与二次开发:从ChatPaper到gpt_academic

前言 本文的前两个部分最早是属于此旧文的《学术论文GPT的源码解读与微调&#xff1a;从ChatPaper到七月论文审稿GPT第1版》&#xff0c;但为了每一篇文章各自的内容更好的呈现&#xff0c;于是我今天做了以下三个改动 原来属于mamba第五部分的「Mamba近似工作之线性Transfor…

【YOLO v5 v7 v8 v9小目标改进】RevCol:解决深度学习信息从低层(输入)传递至高层(输出)的过程中,信息会逐层丢失问题

RevCol&#xff1a;解决深度学习信息从低层&#xff08;输入&#xff09;传递至高层&#xff08;输出&#xff09;的过程中&#xff0c;信息会逐层丢失问题 学习解耦表示可逆列网络&#xff08;RevCol&#xff09;子特征1&#xff1a;多级可逆单元子特征2&#xff1a;可逆列架构…

实践航拍小目标检测,基于YOLOv7【tiny/l/x】不同系列参数模型开发构建无人机航拍场景下的小目标检测识别分析系统

关于无人机相关的场景在我们之前的博文也有一些比较早期的实践&#xff0c;感兴趣的话可以自行移步阅读即可&#xff1a; 《deepLabV3Plus实现无人机航拍目标分割识别系统》 《基于目标检测的无人机航拍场景下小目标检测实践》 《助力环保河道水质监测&#xff0c;基于yolov…

LLM | GPT-NEOX论文详解

GPT-NEOX使用旋转位置编码。模型权重使用float16表示。最大序列长度为2048。 论文题目&#xff1a;2022.04.14_GPT-NeoX-20B: An Open-Source Autoregressive Language Model 论文地址&#xff1a;2204.06745.pdf (arxiv.org) 论文代码&#xff1a;EleutherAI/gpt-neox: An imp…