Hadoop_MapReduce_WordCount案例

这篇博客详细介绍了如何使用Java实现一个MapReduce程序,用于统计文本文件中每个单词出现的次数。从创建Maven工程,配置依赖,编写Mapper、Reducer和Driver类,到在本地运行测试,再到提交到Hadoop集群进行测试,每个步骤都有清晰的说明和代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

1、需求

(1)输入数据

(2)期望输出数据

2、实现(本地测试)

(1)环境准备

        1)创建maven工程,MapReduceDemo(maven官网下载maven,利用阿里镜像速度快,仓库选择自己建的文件夹,默认在c盘)

        2)在pom.xml文件中添加如下依赖

        3)在项目的src/main/resources目录下,新建一个文件,命名为“log4j.properties”,在文件中填入。

        4)创建包名:com.atguigu.mapreduce.wordcount

(2)三个类

        1)Mapper类

        2)Reducer类

        3)Driver类

 3、提交到集群测试

(1)用maven打jar包,需要添加的打包插件依赖

(2)将程序打成jar包 

(3)拷贝该jar包到Hadoop集群的/opt/module/hadoop-3.1.3路径(可以直接拖进shell中这个目录)

(4)执行WordCount程序(执行前确保集群启动)


1、需求

在给定的文本文件中统计输出每一个单词出现的总次数

(1)输入数据

txt文件

(2)期望输出数据

atguigu	2
banzhang	1
cls	2
hadoop	1
jiao	1
ss	2
xue	1

2、实现(本地测试)

 按照MapReduce编程规范,分别编写Mapper,Reducer,Driver。

(1)环境准备

        1)创建maven工程,MapReduceDemo(maven官网下载maven,利用阿里镜像速度快,仓库选择自己建的文件夹,默认在c盘)

        2)在pom.xml文件中添加如下依赖

<dependencies>
    <dependency>
        <groupId>org.apache.hadoop</groupId>
        <artifactId>hadoop-client</artifactId>
        <version>3.1.3</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.30</version>
    </dependency>
</dependencies>

        3)在项目的src/main/resources目录下,新建一个文件,命名为“log4j.properties”,在文件中填入。

log4j.rootLogger=INFO, stdout  
log4j.appender.stdout=org.apache.log4j.ConsoleAppender  
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout  
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n  
log4j.appender.logfile=org.apache.log4j.FileAppender  
log4j.appender.logfile.File=target/spring.log  
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout  
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n

        4)创建包名:com.atguigu.mapreduce.wordcount

(2)三个类

!注意:导包要仔细

        1)Mapper类

package com.atguigu.mapreduce.wordcount2;

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

import java.io.IOException;

/**
 * KEYIN,map阶段输入的key的类型:LongWritable
 * VALUEIN,map阶段输入的value的类型:Text
 * KEYOUT,map阶段输出的key的类型:Text
 * VALUEOUT,map阶段输出的value的类型:IntWritable
 */
public class WordCountMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
    private Text outK = new Text();
    private IntWritable outV = new IntWritable(1);

    /**
     * @param context, 联络作用,联络Map和Reduce
     */
    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        //String的方法多,因此转为String
        //1 获取一行,得到:atguigu atguigu
        String line = value.toString();

        //2 切割,得到:
        //atguigu
        //atguigu
        String[] words = line.split(" ");

        //3 循环写出
        for (String word : words) {
            //封装outK
            outK.set(word);

            //写出
            context.write(outK,outV);
        }
    }
}

        2)Reducer类

package com.atguigu.mapreduce.wordcount2;

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

import java.io.IOException;

/**
 * KEYIN,reduce阶段输入的key的类型:Text
 * VALUEIN,reduce阶段输入的value的类型:IntWritable
 * KEYOUT,reduce阶段输出的key的类型:Text
 * VALUEOUT,reduce阶段输出的value的类型:IntWritable
 */
public class WordCountReducer extends Reducer<Text, IntWritable,Text, IntWritable> {
    IntWritable outV = new IntWritable();

    /**
     * Iterable<IntWritable> values,相当于集合
     */
    @Override
    protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
        //传入的数值 atguigu(1,1) atguigu出现两次
        int sum = 0;
        //累加
        for (IntWritable value : values) {
            sum += value.get();
        }

        outV.set(sum);

        //写出
        context.write(key,outV);
    }
}

        3)Driver类

package com.atguigu.mapreduce.wordcount;

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.output.FileOutputFormat;

import java.io.IOException;


public class WordCountDriver {
    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
        //1、获取job
        Configuration conf = new Configuration();
        Job job = Job.getInstance(conf);

        //2、设置jar包路径
        job.setJarByClass(WordCountDriver.class);

        //3、关联mapper和reducer
        job.setMapperClass(WordCountMapper.class);
        job.setReducerClass(WordCountReducer.class);

        //4、设置map输出的kv类型
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(IntWritable.class);

        //5、设置最终输出的kv类型(不一定是reducer的输出类型)
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);

        //6、设置输入路径和输出路径
        FileInputFormat.setInputPaths(job, new Path("D:\\code\\Hadoop\\input\\inputword"));
        FileOutputFormat.setOutputPath(job, new Path("D:\\code\\Hadoop\\test\\output"));

        //7、提交job
        boolean result = job.waitForCompletion(true);

        System.exit(result ? 0 : 1);
    }
}

 3、提交到集群测试

为了使输入和输出路径可变,利用args,修改driver类

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

(1)用maven打jar包,需要添加的打包插件依赖

<build>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.6.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
        <plugin>
            <artifactId>maven-assembly-plugin</artifactId>
            <configuration>
                <descriptorRefs>
                    <descriptorRef>jar-with-dependencies</descriptorRef>
                </descriptorRefs>
            </configuration>
            <executions>
                <execution>
                    <id>make-assembly</id>
                    <phase>package</phase>
                    <goals>
                        <goal>single</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

(2)将程序打成jar包 

 

 

(3)拷贝该jar包到Hadoop集群的/opt/module/hadoop-3.1.3路径(可以直接拖进shell中这个目录)

(4)执行WordCount程序(执行前确保集群启动)

[atguigu@hadoop102 hadoop-3.1.3]$ hadoop jar  wc.jar
 com.atguigu.mapreduce.wordcount.WordCountDriver /user/atguigu/input /user/atguigu/output

注意要copy driver类的reference,操作:选中左边文件,右键copy->copy reference

### 使用Hadoop MapReduce编程实现五个及以上需求的示例 #### 1. 单词计数 (Word Count public class WordCount { public static class TokenizerMapper extends Mapper<Object, Text, Text, IntWritable> { private final static IntWritable one = new IntWritable(1); private Text word = new Text(); @Override protected void map(Object key, Text value, Context context) throws IOException, InterruptedException { StringTokenizer itr = new StringTokenizer(value.toString()); while (itr.hasMoreTokens()) { word.set(itr.nextToken()); context.write(word, one); } } } public static class IntSumReducer extends Reducer<Text,IntWritable,Text,IntWritable> { private IntWritable result = new IntWritable(); @Override protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { int sum = 0; for (IntWritable val : values) { sum += val.get(); } result.set(sum); context.write(key, result); } } } ``` 此代码展示了如何创建一个简单的映射器和化简器来计算文档中各个词语的数量[^3]。 #### 2. 平均值计算 (Average Calculation) 平均值计算可以用来求解一组数值数据集的算术平均数。这通常涉及到两个阶段:先汇总总数与项数,再除以总数量得到最终结果。 ```java // 假设有一个自定义的Combiner用于局部聚合... public static class AvgMapper extends Mapper<LongWritable, Text, Text, DoubleArrayWritable> { ... } public static class AvgReducer extends Reducer<Text, DoubleArrayWritable, Text, FloatWritable> { ... } ``` 这里`DoubleArrayWritable`被设计成携带一对双精度浮点数——分别是累加后的总和及其对应的条目数目。 #### 3. 数据过滤 (Data Filtering) 通过设定特定条件筛选符合条件的数据记录。比如只保留年龄大于等于某个阈值的人的信息: ```java public static class FilterMapper extends Mapper<LongWritable, Text, NullWritable, Text> { private final static NullWritable NULL_KEY = NullWritable.get(); private Text lineRecord; @Override protected void setup(Context context) throws IOException, InterruptedException { super.setup(context); this.lineRecord = new Text(); } @Override protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { String[] fields = value.toString().split(","); if(Integer.parseInt(fields[1]) >= THRESHOLD_AGE){ lineRecord.set(value); context.write(NULL_KEY,lineRecord ); } } } // 这里不需要reducer因为只需要输出满足条件的结果即可。 ``` 这段代码实现了基于给定字段(如年龄)进行简单过滤的功能。 #### 4. 排序操作 (Sorting Operation) 对于大规模数据集来说,在分布式环境中执行排序是一项重要任务。可以通过设置适当的键比较逻辑来自定义排序顺序。 ```java public static class SortMapper extends Mapper<LongWritable, Text, CustomKey, NullWritable> {...} public static class SortReducer extends IdentityReducer<CustomKey,NullWritable>{...} ``` 其中`CustomKey`应该继承于`WritableComparable<T>`接口并重写其compareTo方法以便支持自定义排序规则。 #### 5. 统计分析 (Statistical Analysis) 利用MapReduce框架来进行一些基本的概率分布估计或其他形式的统计学研究也是可行的;例如估算泊松分布参数λ或构建直方图等。 ```java public static class StatisticMapper extends Mapper<LongWritable, Text, Text, LongWritable> {...} public static class StatisticReducer extends Reducer<Text, LongWritable, Text, LongWritable> {...} ``` 这些组件可以根据具体应用场景调整内部算法细节以适应不同的统计模型。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值