既然环境都搭建起来了,那么就来实际跑一个hadoop界的hello world程序。—-wordcount,(下面程序并非源码)。
1.新建一个maven项目,输入groupId和ArtifactId.
2.修改pom.xml文件。
加上hadoop的依赖,版本对应集群版本
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-client</artifactId>
<version>2.7.3</version>
</dependency>
设置编译级别为1.8来消除警告。
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
3.在src/main/java里创建类,这里我取名为TestHello
一个hadoop程序,包括三个类,map,reduce和主类,我们都写在一个文件中,采用内部类的方式。
首先,创建第一个map类。继承Mapper类,并重写map方法。注意导包全为hadoop相关类型的包,不要导错了。
mapper类一共有5个方法可以重写,这里我们的输入格式是Text,默认是以行输入,所以一个文件会执行多次map,但是只会执行一次setup和cleanup。当需要单输出的时候,就可以重写这两个方法。
String[] words = value.toString().split("\\s+");
for (String s :words) {
context.write(new Text(s),one);
}
将输入源转换为字符串后,再用split函数按照一定的规则打散,再遍历就好了。
context.write()有两个参数,key和value,类型对应前面Mapper类对应的后两个泛型参数。他讲作为map方法的输出,也是reduce方法的输入。
这里的one前面定义了IntWritable one = new IntWritable(1);,就是新建一个值为1 的intwritable对象,为了避免多次创建,所以定义为常量,多次使用。
作用为,遍历打散后的单词,每个计数为1。
接下来就是reduce类了。
class HelloReduce extends Reducer<Text,IntWritable,Text,IntWritable>{
int count = 0;
@Override
protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
for (IntWritable v :values) {
count++;
}
context.write(key,new IntWritable(count));
}
}
map做完后,系统会自动洗牌,把map的结果,
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(conf);
Path home = fs.getHomeDirectory();
//当output文件夹存在的时候,先删除
Path output = new Path(home,args[1]);
if (fs.exists(output)) {
fs.delete(output,true);
}
//不加这句就会找不到对应的class。。。。。。 conf.set("mapred.jar","/home/hadoop/IdeaProjects/bigdata/target/bigdata-1.0-SNAPSHOT.jar");
//新建一个job对象
Job job = Job.getInstance(conf,"wordcount");
job.setJarByClass(MyWordCount.class);
//设置对应的map的reduce类
job.setMapperClass(TextMap.class);
job.setReducerClass(TextReduce.class);
//设置输出类型,(输入可省)
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
//设置输入输出参数,可写绝对路径
FileInputFormat.addInputPath(job,new Path(args[0]));
FileOutputFormat.setOutputPath(job,new Path(args[1]));
System.out.println(job.waitForCompletion(true));
可以看到上面代码我们还需要去设置两个参数给程序,
Edit configuration–>add a application–>
总结:
整个mapreduce的执行流程为:
输入 –>切片(默认text input format,逐行读写,一个切片对应一个map)–>map–>洗牌(shuffle)–>sort—>reduce(合并)–>输出
需要我们操作的就是map和reduce过程,继承mapper和reducer类,重写他的方法,来对数据进行处理。