用MapReduce实现WordCount(简单尝试MapReduce)

前言

MapReduce不需要“分割”,框架已经做好这一步了。

只需要进行“线程步骤”——Mapper,而且无需计算如何分割(这是Combine的工作)

和“聚合结果”——Reducer,而且无需设计如何聚合(Shuffle的工作)

这里提到的步骤、类在后面的文章中会一一拆解分析,这里仅作简单尝试。

准备

为了让程序在IDEA中测试运行,需要在win中设置一下Hadoop环境:

把Hadoop压缩包以管理员身份解压(不行就放c盘,c盘自动认为是管理员身份);两个配置文件,winutils.exe放在bin,hadoop.dlll放在windows/system32。

开始写

1.Mapper

继承Mapper 类,重写map 方法。让分割方式为“ ”。

public class WordMapper extends Mapper<LongWritable, Text,Text,LongWritable> {
    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        String[] words = value.toString().split(" ");
        for(String word : words){
            context.write(new Text(word),new LongWritable(1));
        }
    }
}

2.Reducer

继承Reducer 类,重写reduce 方法。

public class WordReduce extends Reducer<Text, LongWritable,Text,LongWritable> {
    @Override
    protected void reduce(Text key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException {
        int count=0;
        for (LongWritable lw:values){
            count+=lw.get();
        }
        context.write(key,new LongWritable(count));
    }
}

3.Job

写出main方法,运行得到文件。

public class WordJob {
    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
        Job job = Job.getInstance(new Configuration());
        job.setJarByClass(WordJob.class);//告诉 主类就是我

        FileInputFormat.setInputPaths(job,new Path("file:///d:/temp/a.txt"));//文件
        FileOutputFormat.setOutputPath(job,new Path("file:///d:/temp/write"));//目录,事先不能存在

        job.setMapperClass(WordMapper.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(LongWritable.class);

        job.setReducerClass(WordReduce.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(LongWritable.class);
        //设置reduce个数
        //job.setNumReduceTasks(2);

        job.waitForCompletion(true);
    }
}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Woovong

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值