IDEA调试运行基于hadoop的WordCount项目

IDEA调试运行hadoop

创建一个WordCount项目

创建一个com.lyf.wordcount包

1.修改maven pom.xml

//配置打包方式

<packaging>jar</packaging>

//配置依赖jar

<dependency>

      <groupId>org.apache.hadoop</groupId>

      <artifactId>hadoop-common</artifactId>

      <version>2.6.5</version>

    </dependency>

    <dependency>

      <groupId>org.apache.hadoop</groupId>

      <artifactId>hadoop-hdfs</artifactId>

      <version>2.7.3</version>

</dependency>

//配置maven打包插件

<build>

    <defaultGoal>install</defaultGoal>

    <plugins>

      <plugin>

        <groupId>org.apache.maven.plugins</groupId>

        <artifactId>maven-compiler-plugin</artifactId>

        <version>3.8.0</version>

        <configuration>

          <source>1.8</source>

          <target>1.8</target>

        </configuration>

      </plugin>

      <plugin>

        <groupId>org.apache.maven.plugins</groupId>

        <artifactId>maven-resources-plugin</artifactId>

        <version>3.1.0</version>

        <configuration>

          <encoding>UTF-8</encoding>

        </configuration>

      </plugin>

      <!-- Allows the example to be run via 'mvn compile exec:java' -->

      <plugin>

        <groupId>org.codehaus.mojo</groupId>

        <artifactId>exec-maven-plugin</artifactId>

        <version>1.6.0</version>

        <configuration>

          <mainClass>com.test.mapreduce.MainApp</mainClass>

          <includePluginDependencies>false</includePluginDependencies>

        </configuration>

      </plugin>

    </plugins>

</build>

2.创建一个WordMapper类

 

package com.lyf.wordcount;

 

import java.io.IOException;

import java.util.StringTokenizer;

 

import org.apache.hadoop.io.IntWritable;

import org.apache.hadoop.io.Text;

import org.apache.hadoop.mapreduce.Mapper;

 

// 创建一个 WordMapper 继承于 Mapper抽象类

public class WordMapper extends Mapper<Object, Text, Text, IntWritable>

{

       private final static IntWritable one = new IntWritable(1);

       private Text word = new Text();

      

       // Mapper抽象类的核心方法,三个参数

       public void map(Object key, // 首字符偏移量

                     Text value, // 文件的一行内容

                     Context context) // Mapper端的上下文,与OutputCollectorReporter的功能类似

                     throws IOException, InterruptedException

       {

              StringTokenizer itr = new StringTokenizer(value.toString());

              while (itr.hasMoreTokens())

              {

                     word.set(itr.nextToken());

                     context.write(word, one);

              }

       }

}

3.创建一个WordReducer类

 

package com.lyf.wordcount;

 

import java.io.IOException;

 

import org.apache.hadoop.io.IntWritable;

import org.apache.hadoop.io.Text;

import org.apache.hadoop.mapreduce.Reducer;

 

// 创建一个 WordReducer 继承于 Reducer抽象类

public class WordReducer extends Reducer<Text, IntWritable, Text, IntWritable>

{

       private IntWritable result = new IntWritable(); // 用于记录 key 的最终的词频数

      

       // Reducer抽象类的核心方法,三个参数

       public void reduce(Text key, // Map 输出的 key

                     Iterable<IntWritable> values, // Map端输出的Value 集合(相同key的集合)

                     Context context) // Reduce 端的上下文,与OutputCollectorReporter的功能类似

                     throws IOException, InterruptedException

       {

              int sum = 0;

              for (IntWritable val : values) // 遍历 values集合,并把值相加

              {

                     sum += val.get();

              }

              result.set(sum); // 得到最终词频数

              context.write(key, result); // 写入结果

       }

}

4.创建一个WordMain类

package com.lyf.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 org.apache.hadoop.util.GenericOptionsParser;

 

public class WordMain

{

       public static void main(String[] args) throws Exception

       {

              // Configuration类:读取Hadoop的配置文件,如 site-core.xml...

              // 也可用set方法重新设置(会覆盖):conf.set("fs.default.name", "hdfs://xxxx:9000")

              Configuration conf = new Configuration();

             

              // 将命令行中参数自动设置到变量conf

              String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();

             

              /**

               * 这里必须有输入输出

               */

             

              if (otherArgs.length != 2)

              {

                     System.err.println("Usage: wordcount <in> <out>");

                     System.exit(2);

              }

             

              Job job = new Job(conf, "word count"); // 新建一个 job,传入配置信息

              job.setJarByClass(WordMain.class); // 设置 job 的主类

              job.setMapperClass(WordMapper.class); // 设置 job Mapper

              job.setCombinerClass(WordReducer.class); // 设置 job 作业合成类

              job.setReducerClass(WordReducer.class); // 设置 job Reducer

              job.setOutputKeyClass(Text.class); // 设置 job 输出数据的关键类

              job.setOutputValueClass(IntWritable.class); // 设置 job 输出值类

              FileInputFormat.addInputPath(job, new Path(otherArgs[0])); // 文件输入

              FileOutputFormat.setOutputPath(job, new Path(otherArgs[1])); // 文件输出

              System.exit(job.waitForCompletion(true) ? 0 : 1); // 等待完成退出

       }

}

5.执行MapReduce操作

1.将写好的代码打包

2maven package后的jar包位于target路径下

3.测试文件Phone_Data.dat上传hdfs集群

       hdfs dfs -put Phone_Data.dat

4.执行测试命令

       hadoop jar WordCount-1.0-SNAPSHOT.jar \

       com/test/wordcount/WordMain /Phone_Data.dat  /output

       //注解

  1. WordCount-1.0-SNAPSHOT.jar是代码jar
  2. com/test/wordcount/WordMain是因为main程序是放在com/test/wordcount路径下的WordMain.java
  3. /Phone_Data.dathdfs集群中输入文件的路径
  4. /outputhdfs集群中输出文件的路径

5.执行成功,part-r-00000中即为执行结果

 

### Hadoop WordCount 示例教程 HadoopWordCount 是一个经典的 MapReduce 示例程序,用于演示如何利用分布式计算框架来完成简单的词频统计任务。以下是关于 Hadoop WordCount 示例的相关说明: #### 1. 命令行执行 WordCount 示例 可以通过以下命令运行 Hadoop 自带的 WordCount 示例程序[^1]: ```bash hadoop jar share/hadoop/mapreduce/hadoop-mapreduce-examples-3.3.1.jar wordcount /test/words /test/out ``` 上述命令中的参数解释如下: - `share/hadoop/mapreduce/hadoop-mapreduce-examples-3.3.1.jar`:WordCount 示例所在的 JAR 文件路径。 - `/test/words`:输入文件所在目录。 - `/test/out`:输出结果存储的目录。 如果需要根据不同的 Hadoop 版本调整路径,则可以修改为对应的版本号和安装路径[^2]。 #### 2. 数据准备与上传 为了运行 WordCount 程序,需先将待处理的数据文件上传到 HDFS 上。假设使用的数据文件名为 `airport-codes-na.txt`,操作步骤如下[^3]: 1. 创建 HDFS 输入目录: ```bash hdfs dfs -mkdir -p /input ``` 2. 将本地数据文件上传至 HDFS: ```bash hdfs dfs -put local/path/to/airport-codes-na.txt /input/ ``` #### 3. 结果查看 运行完成后,可以在指定的输出目录中找到结果文件,默认命名为 `part-r-00000`。使用以下命令查看部分内容: ```bash hdfs dfs -cat /output/part-r-00000 | head -n 10 ``` #### 4. IDEA 集成开发环境配置 对于希望在 IDE 中调试运行 WordCount 示例的情况,可参考以下配置[^4]: - 修改核心站点配置文件(core-site.xml)以支持跨平台提交任务: ```xml <property> <name>mapreduce.app-submission.cross-platform</name> <value>true</value> </property> ``` - 设置自定义打包后的 JAR 路径供 Mapper 和 Reducer 使用: ```xml <property> <name>mapred.jar</name> <value>E:\Projects\hadoop\HadoopExercise\target\HadoopExercise-1.0-SNAPSHOT.jar</value> </property> ``` #### 5. 源码解析 WordCount 程序的核心逻辑分为两部分——Mapper 和 Reducer[^5]: - **Mapper**:读取每行文本并将其拆分成单词,输出键值对 `<单词, 1>`。 - **Reducer**:接收来自 Mapper 的中间结果,按相同键聚合所有值,并累加得到最终频率。 以下是简化版的 Java 实现代码: ```java 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 { String line = value.toString(); StringTokenizer tokenizer = new StringTokenizer(line.toLowerCase()); while (tokenizer.hasMoreTokens()) { word.set(tokenizer.nextToken()); context.write(word, one); } } } public static class SumReducer extends Reducer<Text, IntWritable, Text, 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(); } context.write(key, new IntWritable(sum)); } } public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); Job job = Job.getInstance(conf, "word count"); job.setJarByClass(WordCount.class); job.setMapperClass(TokenizerMapper.class); job.setCombinerClass(SumReducer.class); job.setReducerClass(SumReducer.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); } } ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值