如何在开发环境中创建mapreduce程序

本文将指导你如何在开发环境中一步步构建MapReduce程序。首先,你需要搭建包含Eclipse和Hadoop的开发环境,接着创建一个自定义的Java包,如mapreduce,并在其中编写mapreduce.java文件。然后,将MapReduce的代码添加到该文件中,最终完成MapReduce程序的编写。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 首先建立开发环境(eclipse-hadoop),网上搭建博客很多,不细说

2. 开发环境建立之后自己建立一个包,这个名字是随便起的,可以起名为mapreduce。

3.然后建立一个.java文件,可以是mapreduce文件:mapreduce.java

4.把下面代码放入放入mapreduce.java

5.建立mapreduce程序。

package mapreduce;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
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.output.*;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.partition.HashPartitioner;

public class mapreduce {

static final String INPUT_PATH = "hdfs://master:8020/input";
static final String OUT_PATH = "hdfs://master:8020/Output";

public static void main(String[] args) throws Exception {
//主类
Configuration conf = new Configuration();
final Job job = new Job(conf, mapreduce.class.getSimpleName());
job.setJarByClass(mapreduce.class);
// 寻找输入
FileInputFormat.setInputPaths(job, INPUT_PATH);
// 1.2对输入数据进行格式化处理的类
job.setInputFormatClass(TextInputFormat.class);
job.setMapperClass(MyMapper.class);

// 1.2指定map输出类型<key,value>类型
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(LongWritable.class);

// 1.3指定分区
job.setPartitionerClass(HashPartitioner.class);
job.setNumReduceTasks(1);

// 1.4排序分组省略,使用默认
// 1.5规约省略,使用默认
job.setReducerClass(MyReduce.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(LongWritable.class);
// 指定输出路径
FileOutputFormat.setOutputPath(job, new Path(OUT_PATH));
// 指定输出的格式或则类
job.setOutputFormatClass(TextOutputFormat.class);

// 把作业提交给jobtracer
job.waitForCompletion(true);

}
//map类
static class MyMapper extends
Mapper<LongWritable, Text, Text, LongWritable> {
protected void map(LongWritable key, Text value, Context context)
throws IOException, InterruptedException {
final String[] splited = value.toString().split("\t");
for (String word : splited) {
context.write(new Text(word), new LongWritable(1L));

}

}

}
//reduce类
static class MyReduce extends
Reducer<Text, LongWritable, Text, LongWritable> {
@Override
protected void reduce(Text k2, java.lang.Iterable<LongWritable> v2s,
Context ctx) throws java.io.IOException, InterruptedException {
long times = 0L;
for (LongWritable count : v2s) {
times += count.get();
ctx.write(k2, new LongWritable(times));
}

}

}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值