资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

Hadoop实践(二)Mapreduce编程

Mapreduce 编程,本文以WordCount  为例:实现文件字符统计

创新互联致力于网站建设,网站制作设计,营销网页按需策划设计,外贸网站建设,企业网站建设,小程序制作,网站SEO优化,网站设计制作案例丰富,是成都做网站公司和建站公司,欢迎咨询。

    在eclipse 里面搭建一个java项目,引入hadoop lib目录下的jar,和 hadoop主目录下的jar。

    新建WordCount 类:

package org.scf.wordcount;

import java.io.IOException;

import java.util.*;

import org.apache.hadoop.fs.Path;

import org.apache.hadoop.conf.*;

import org.apache.hadoop.io.*;

import org.apache.hadoop.mapred.*;

import org.apache.hadoop.util.*;

public class WordCount {

public static class Map extends MapReduceBase implements Mapper {

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

     private Text word = new Text();

     public void map(LongWritable key, Text value, OutputCollector output, Reporter reporter) throws IOException {

      String line = value.toString();

       StringTokenizer tokenizer = new StringTokenizer(line);

       while (tokenizer.hasMoreTokens()) {

         word.set(tokenizer.nextToken());

         output.collect(word, one);

       }

     }

   }

  public static class Reduce extends MapReduceBase implements Reducer {

     public void reduce(Text key, Iterator values, OutputCollector output, Reporter reporter) throws IOException {

      int sum = 0;

       while (values.hasNext()) {

         sum += values.next().get();

       }

       output.collect(key, new IntWritable(sum));

     }

   }

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

     JobConf conf = new JobConf(WordCount.class);

     conf.setJobName("wordcount");

     conf.setOutputKeyClass(Text.class);

     conf.setOutputValueClass(IntWritable.class);

     conf.setMapperClass(Map.class);

     conf.setCombinerClass(Reduce.class);

     conf.setReducerClass(Reduce.class);

     conf.setInputFormat(TextInputFormat.class);

     conf.setOutputFormat(TextOutputFormat.class);

     FileInputFormat.setInputPaths(conf, new Path(args[0]));

     FileOutputFormat.setOutputPath(conf, new Path(args[1]));

     JobClient.runJob(conf);

   }

}

2.编译,运行该类

    

 cd /home/Hadoop/

mkdir wordcount_classes

javac -classpath /usr/hadoop-1.0.4/hadoop-core-1.0.4.jar -d /home/Hadoop/wordcount_classes WordCount.java

 jar -cvf /home/Hadoop/wordcount.jar -C /home/Hadoop/wordcount_classes/ .

 hadoop dfs -put /home/Hadoop/test.txt  /user/root/wordcount/input/file2

 hadoop dfs -put /home/Hadoop/test1.txt  /user/root/wordcount/input/file3

 hadoop jar /home/Hadoop/wordcount.jar org.scf.wordcount.WordCount /user/root/wordcount/input /user/root/wordcount/output

hadoop dfs -ls /user/root/wordcount/output

 hadoop dfs -cat /user/root/wordcount/output/part-00000




标题名称:Hadoop实践(二)Mapreduce编程
文章位置:http://cdkjz.cn/article/gojghj.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220