一.基础环境:
本文默认了你已经有一点的java基础,本机环境已安装java、maven、ide,配置好了相关的环境变量,且已经有可用的hadoop环境,已经用idea新建一个java maven项目。还要有一台linux客户机,可执行hadoop命令的。
以上环境有没完成的,自行去百度完成。
二.pom.xml引入包:
org.apache.hadoop
hadoop-common
2.7.3
org.apache.hadoop
hadoop-hdfs
2.7.3
org.apache.hadoop
hadoop-client
2.7.3
三.准备统计文件并上传
1.新建一个文件word_test.txt
I have searched a thousand years,And I have cried a thousand tears。
I found everything I need,You are everything to me。
2.上传到hadoop
先 rz 上传到linux客户机,再执行下边命令上传到hdfs
hadoop fs -mkdir /tmp/mr_test/
hadoop fs -put ./word_test.txt /tmp/mr_test/
四.上代码(官方WordCount V1)
package com.yixin;
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.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import java.io.IOException;
import java.util.StringTokenizer;
public class WordCount {
public static class TokenizerMapper
extends Mapper
五.打包上传执行
1.用ide或maven打包代码成jar,
2.rz上传到linux客户机
3.执行代码
hadoop jar mrtest-1.0-SNAPSHOT.jar com.yixin.WordCount /tmp/mr_test/word_test.txt /tmp/mr_test/output
4.查看结果
hadoop fs -cat /tmp/mr_test/output
public static class TokenizerMapper
extends Mapper
2.运行方式a,和v1参数一样
打包上传和v1一样不说了,运行是如下命令:
hadoop fs -rm -r /tmp/mr_test/output
hadoop jar mrtest-1.0-SNAPSHOT.jar com.yixin.WordCount2 /tmp/mr_test/word_test.txt /tmp/mr_test/output
结果:
hadoop fs -cat /tmp/mr_test/output/*
3.新建文件patterns.txt(跳过字符的规则),并上传到集群。
新建,编辑,保存
vim patterns.txt
.
,
!
to
,
。
上传:
hadoop fs -put patterns.txt /tmp/mr_test/
运行方法b,多加2个参数,跳过不需要统计的字符
hadoop fs -rm -r /tmp/mr_test/output
hadoop jar mrtest-1.0-SNAPSHOT.jar com.yixin.WordCount2 /tmp/mr_test/word_test.txt /tmp/mr_test/output -skip /tmp/mr_test/patterns.txt
结果:
hadoop fs -cat /tmp/mr_test/output/*
相关字符已经过滤掉。
七.MR简化配置工具ToolRunner:
可以使这个工具来预配置,这样能简化使用方的代码量,如精简main方法,只需要2行代码,这个我就不写例子,推荐大家看这个文章:
使用ToolRunner运行Hadoop程序基本原理分析_jediael_lu的专栏-CSDN博客