mapreduce之WordCount

注:map阶段会读取一行进行整合

1.创建项目如下:

2.进行导包:

导入的jar包如下:

 

 

 

 3.选中lib中的所有jar包,点击右键,Build Path,Add to Build Path 

4.开发

在src上点击右键,New-->Package

map阶段:

<key,value>

map阶段读取:key(行),value(一行的值)

map 阶段输出:key,value 为程序员定义

本例为:key(单词)value(出现次数)

//LongWritable 输入key
    //Text 输入 value
    //Text 输出 key
    //IntWritable

5.reduce阶段:

参数从左到右:

输入key,输入value 输出key,输出value

package hzy.com.wordcounthight;

import java.io.IOException;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

public class wordcounthightreduce extends Reducer<Text, IntWritable, Text, IntWritable>{
    
    @Override
    protected void reduce(Text arg0, Iterable<IntWritable> arg1,
            Reducer<Text, IntWritable, Text, IntWritable>.Context arg2)
            throws IOException, InterruptedException {
            int sum = 0;
            for (IntWritable intWritable : arg1) {
                sum = sum + intWritable.get();    
            }
            arg2.write(arg0,new IntWritable(sum));
    }

}

6。main函数

package hzy.com.wordcounthight;

import java.io.IOException;

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;

public class wordcounthighapp {
    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
        //1.连接hadoop
        Configuration configuration = new Configuration();
        configuration.set("fs.defaultFS","hdfs://hadoop0:9000/");
        
        //2,创建job,设置入口
        Job job = Job.getInstance(configuration);
        job.setJarByClass(wordcounthighapp.class);
        //读取文件
        FileInputFormat.setInputPaths(job, new Path("/data/source.txt"));
        
        //进行mapper计算
        
        job.setMapperClass(wordcounthighmapper.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(IntWritable.class);
        
        //进行reduce计算
        job.setReducerClass(wordcounthightreduce.class);
       job.setOutputKeyClass(Text.class);
       job.setOutputValueClass(IntWritable.class);
       
       //写结果到hdfs:
       FileOutputFormat.setOutputPath(job, new Path("/data/xuting"));
       
       //提交任务
       job.waitForCompletion(true);

        
    }

}

 

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值