Hadoop 之Mapreduce wordcount词频统计案例(详解)

  • MapReduce是什么?
    Map Reduce是Google公司开源的一项重要技术,它是一个编程模型,用以进行大数据量的计算。MapReduce采用“分而治之”思想,把对大规模数据集的操作,分发给一个主节点管理下的各个子节点共同完成,然后整合各个子节点的中间结果,得到最终的计算结果。

  • MapReduce实现WordCount的实现思路:
    将hdfs上的文本作为输入,MapReduce通过InputFormat会将文本进行切片处理(按行读入),每出现一个单词就标记一个数字1,经过在map函数处理,输出中间结果<单词,1>的形式,并在reduce函数中完成对每个单词的词频统计。

软件:IntelliJ IDEA

一、创建项目 :example-hdfs

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

二、项目目录

在这里插入图片描述

三、WordCountMapper.class

继承Mapper类实现自己的Mapper类,并重写map()方法

package cn.it.cast.hadoop.mr;

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;

public class WordCountMapper extends Mapper<LongWritable,Text,Text,IntWritable> {
    @Override   
    //每传入一个<k,v>,该方法就被调用一次
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        //拿到传入的传入进来的一行内容,把数据类型转化为String
        String line = value.toString();
        //将这一行内容按照分隔符进行一行内容的切割,切割成一个单词数组
        String[] words = line.split(" ");
        //遍历数组,每出现一个单词,就标记一个数字1,<单词,1>
        for(String word:words){
            context.write(new Text(word),new IntWritable(1));
        }//使用mr程序的上下文context,把Map阶段处理的数据发送出去,作为reduce节点的输入数据
    }
}

四、WordCountReducer.class

继承Reducer类,实现自己的Reduce类,并重写reduce()方法

package cn.it.cast.hadoop.mr;

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

import java.io.IOException;

public class WordCountReducer extends Reducer<Text, IntWritable, Text,IntWritable> {
    @Override
    //reduce接收所有来自map阶段处理的数据之后,按照key的字典序进行排序
    protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
        //定义一个计数器
        int count = 0;
        //遍历一组迭代器,把每一个数量1累加起来就构成了单词的总次数
        for(IntWritable value:values){
            count += value.get();
        }
        //把最终结果输出
        context.write(key,new IntWritable(count));
    }
}

五、WordCounfDriver.class

程序主入口类:

package cn.it.cast.hadoop.mr;

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;

public class WordCountDriver {
    //把job提交给集群去运行
    public static void main(String[] args) throws Exception{
//        System.setProperty("HADOOP_USER_NAME", "root");
        Job job = Job.getInstance(new Configuration());
        //指定我这个job所在的jar包
        job.setJarByClass(WordCountDriver.class);
        //指定本次mr 所用的mapper reduce类分别是什么
        job.setMapperClass(WordCountMapper.class);
        job.setReducerClass(WordCountReducer.class);
        //指定本次mr mapper阶段的输出 k v类型
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(IntWritable.class);
        //指定本次mr 最终输出的 k v类型
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);
        //指定本次mr 输入的数据路径,和最终输出结果存放在什么位置
        FileInputFormat.setInputPaths(job,new Path(args[0]));
        FileOutputFormat.setOutputPath(job,new Path(args[1]));
        //提交程序,并且监控打印程序执行的结果
        boolean b = job.waitForCompletion(true);
        System.exit(b?0:1);
    }
}

六、pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>example-mr</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>jdk.tools</groupId>
            <artifactId>jdk.tools</artifactId>
            <version>1.8</version>
            <scope>system</scope>
            <systemPath>C:/Program Files/Java/jdk1.8.0_131/lib/tools.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-common</artifactId>
            <version>3.2.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-hdfs</artifactId>
            <version>3.2.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-client</artifactId>
            <version>3.2.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-mapreduce-client-core</artifactId>
            <version>3.2.1</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <archive>
                        <manifest>
                            <addClasspath>true</addClasspath>
                            <classpathPrefix>lib</classpathPrefix>
                            <mainClass>cn.it.cast.hadoop.mr.WordCountDriver</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

七、打包jar包

在这里插入图片描述
在target目录有我们刚刚打包的jar(为了方便,重命名 wc.jar)
在这里插入图片描述

八、在SecureCRT软件上传刚刚生成的jar包

把jar包拖动到主节点上
在这里插入图片描述
在这里插入图片描述

九、运行

编写data1.txt 文件
vi data1.txt

hello hadoop
hadoop spark

创建目录/input

hadoop fs mkdir -p /input

上传文件到 /input

hadoop fs -put data1.txt /input

执行 jar包

 hadoop jar wc.jar /input/data1.txt /output/wc

在这里插入图片描述
查看结果:

hadoop fs -cat /output/wc/part-r-00000

在这里插入图片描述
在网页中可以看到生成两个文件
在这里插入图片描述

十、 解决问题:

1、 yum -y install lrzsz
在这里插入图片描述
2、如果运行jar包遇到图片的问题
在这里插入图片描述
可以在每个节点的mapred-site.xml添加以下内容
(/usr/local/hadoop改成你安装hadoop的路径!)

<property>
  <name>yarn.app.mapreduce.am.env</name>
  <value>HADOOP_MAPRED_HOME=/usr/local/hadoop</value>
</property>
<property>
  <name>mapreduce.map.env</name>
  <value>HADOOP_MAPRED_HOME=/usr/local/hadoop</value>
</property>
<property>
  <name>mapreduce.reduce.env</name>
  <value>HADOOP_MAPRED_HOME=/usr/local/hadoop</value>
</property>
  • 18
    点赞
  • 111
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Hadoop MapReduce单词词频统计可以通过以下步骤实现: 1.编写Mapper类 Mapper类是MapReduce程序的核心组件之一,负责将输入数据划分为多个键值对,其键表示输入记录的任意标识符,值表示输入记录的内容。对于单词词频统计程序,我们需要在Mapper将每个单词作为键,将出现次数作为值输出。以下是一个简单的Mapper类实现: ```java public class WordCountMapper extends Mapper<LongWritable, Text, Text, IntWritable> { private final static IntWritable one = new IntWritable(1); private Text word = new Text(); public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { String line = value.toString(); StringTokenizer tokenizer = new StringTokenizer(line); while (tokenizer.hasMoreTokens()) { word.set(tokenizer.nextToken()); context.write(word, one); } } } ``` 在上面的代码,我们使用Java的StringTokenizer工具类将每行输入数据拆分为单个单词,并将它们作为键输出,出现次数作为值输出。其,Mapper的输入键值对类型为LongWritable和Text,输出键值对类型为Text和IntWritable。 2.编写Reducer类 Reducer类是MapReduce程序的另一个核心组件,负责将Mapper输出的键值对进行归约,以便生成最终的输出结果。对于单词词频统计程序,我们需要在Reducer计算每个单词在输入数据出现的总次数,并将其作为输出结果。以下是一个简单的Reducer类实现: ```java public class WordCountReducer extends Reducer<Text, IntWritable, Text, IntWritable> { public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { int sum = 0; for (IntWritable value : values) { sum += value.get(); } context.write(key, new IntWritable(sum)); } } ``` 在上面的代码,我们将Reducer的输入键值对类型设置为Text和IntWritable,输出键值对类型也为Text和IntWritable。Reducer接收到的每个键值对都包含一个单词和它在输入数据出现的次数列表。我们可以遍历这个列表并计算出总次数,然后将其作为值输出。 3.编写Driver类 Driver类是MapReduce程序的控制器,负责设置和启动MapReduce作业的各个组件。以下是一个简单的Driver类实现: ```java public class WordCountDriver { public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); Job job = Job.getInstance(conf, "word count"); job.setJarByClass(WordCountDriver.class); job.setMapperClass(WordCountMapper.class); job.setCombinerClass(WordCountReducer.class); job.setReducerClass(WordCountReducer.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); FileInputFormat.addInputPath(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); System.exit(job.waitForCompletion(true) ? 0 : 1); } } ``` 在上面的代码,我们首先创建一个Configuration对象,并使用它来创建一个Job对象。我们通过setJarByClass()方法指定程序的入口点,并使用setMapperClass()、setCombinerClass()和setReducerClass()方法设置Mapper、Combiner和Reducer类。我们还使用setOutputKeyClass()和setOutputValueClass()方法指定Mapper和Reducer的输出键值对类型。最后,我们使用FileInputFormat.addInputPath()和FileOutputFormat.setOutputPath()方法设置输入和输出路径,并调用job.waitForCompletion()方法提交作业并等待其完成。 4.运行程序 最后,我们可以使用hadoop jar命令来运行MapReduce程序,并将输入数据和输出路径作为命令行参数传递: ``` hadoop jar WordCount.jar WordCountDriver input output ``` 其WordCount.jar是打包后的程序文件WordCountDriver是程序的入口点类,input是输入数据的路径,output是输出结果的路径。运行程序后,我们可以在指定的输出路径看到生成的结果文件

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值