Hadoop运行一个job

本文介绍了如何在Eclipse中安装hadoop-eclipse-plugin插件,配置Hadoop Map/Reduce,以及创建和运行MapReduce程序来实现倒排索引。详细步骤包括插件安装、设置Hadoop目录、新建MapReduce工程以及编写和理解代码。

一:安装eclipse插件

要想在eclipse上进行map-reduce编程,需要安装一个插件,hadoop-eclipse-plugin-1.0.0.jar,可以在这里下载

将插件拷贝到eclipse的plugins目录里即可。打开Eclipse,windows–preferences选择Hadoop Map/Reduce填写hadoop的安装目录



Eclipse所在的机器可以是hadoop集群中的任意一个节点

显示map-reduce视图:windows–show views–others 选择map-reduce,此时我们可以在Eclipse输出栏看到map-reduce视图

右键选择new hadoop location




填入配置文件中的主机名和端口号,到此就配置完了,可以在Eclipse上看到hdfs文件了,用Eclipse可以方便的上传删除查看文件等等

如果你安装插件出现问题,那么最可能的原因就是hadoop安装目录没有填写正确

二:编写Map-Reduce程序

新建map-reduce工程,src目录里新建class文件,工程名和类名一样

实现一个倒排索引

输入:

input1

输出:

out1

思路:

 

silu


代码:


/**
 * map_reduce code 
 * @author wyp
 *
 */
 
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapreduce.*;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
 
 
 
public class Test_Phonenum extends Configured implements Tool{
 
    enum Counter{
         
        LINESKIP,
    }
     
    public static class Map extends Mapper<LongWritable, Text, Text, Text>
    {
        public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException
        {
            String line = value.toString();             
            try
            {
                 
                String [] lineSplit = line.split(" ");
                String anum = lineSplit[0];
                String bnum = lineSplit[1];
                 
                context.write(new Text(bnum), new Text(anum));     
            }
            catch(java.lang.ArrayIndexOutOfBoundsException e)
            {
                context.getCounter(Counter.LINESKIP).increment(1);      
                return;
            }
 
        }
    }
 
    public static class Reduce extends Reducer<Text, Text, Text, Text>
    {
        public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException
        {
            String valueString;
            String out = "";
             
            for(Text value:values)
            {
                valueString  = value.toString();
                out += valueString + "|";
            }
             
            context.write(key, new Text(out));
        }
    }
     
    public int run(String[] args) throws Exception
    {
        Configuration conf = getConf();
         
        Job job = new Job(conf, "WYP_Test_2");     
         
        FileInputFormat.addInputPath(job, new Path(args[0]));      
        FileOutputFormat.setOutputPath(job, new Path(args[1]));    
         
        job.setMapperClass(Map.class);                      
        job.setReducerClass(Reduce.class);                  
         
        job.setOutputFormatClass(TextOutputFormat.class);
        job.setOutputKeyClass(Text.class);             
        job.waitForCompletion(true);
         
        return job.isSuccessful() ? 0 : 1;
    }
     
    public static void main(String[] args) throws Exception{
         
        int res = ToolRunner.run(new Configuration(), new Test_Phonenum(), args);
        System.exit(res);
 
    }
 
}


### 使用 Hadoop 实现蒙特卡罗方法计算圆周率 Hadoop 是一种强大的分布式计算框架,适用于处理大规模数据集的任务。通过 MapReduce 编程模型,可以高效地实现蒙特卡罗方法来估算圆周率 π 的值。 --- #### 核心原理 蒙特卡罗方法的核心思想是基于随机抽样,在单位正方形内生成大量随机点,并统计落入四分之一单位圆内的点数比例。假设总点数为 $N$,其中落在圆内的点数为 $M$,那么 $\pi$ 的近似值可通过下述公式计算得出: $$ \pi \approx 4 \times \frac{M}{N} $$ 为了提升精度,通常需要生成非常大的随机样本量[^1]。 在 Hadoop 环境中,这一过程被分解成多个独立的子任务,由集群节点并行执行,最后汇总结果以获得最终的 π 值。 --- #### 设计思路 以下是使用 Hadoop 和 MapReduce 来实现蒙特卡罗方法的具体设计: 1. **Mapper 阶段** Mapper 负责生成随机点并对每个点进行判断,决定其是否位于四分之一单位圆内。如果满足条件 $(x^2 + y^2) \leq 1$,则记录为有效点。 输入:无实际输入文件,仅需提供虚拟键值对作为触发机制。 输出:每条记录表示一个随机点是否属于圆内(布尔值或计数值)。 2. **Reducer 阶段** Reducer 收集来自各 Mapper 的结果,累加所有有效的点数,并结合总的点数计算出 π 的估值。 3. **驱动程序** 主函数负责初始化作业参数、设置 Mapper 和 Reducer 类型以及定义输出路径等细节。 --- #### 示例代码 以下是一个完整的 Java 实现示例,展示如何用 Hadoop 计算 π 值。 ```java // 导入必要的类库 import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; public class MonteCarloPi { public static class PiMapper extends Mapper<LongWritable, LongWritable, IntWritable, IntWritable> { private final static IntWritable one = new IntWritable(1); private final static IntWritable zero = new IntWritable(0); @Override protected void map(LongWritable key, LongWritable value, Context context) throws IOException, InterruptedException { double x = Math.random(); double y = Math.random(); if ((x * x + y * y) <= 1) { context.write(one, one); // 如果点在圆内 } else { context.write(zero, one); // 否则不在圆内 } } } public static class PiReducer extends Reducer<IntWritable, IntWritable, IntWritable, DoubleWritable> { @Override protected void reduce(IntWritable key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { long countInsideCircle = 0L; // 圆内的点数 long totalCount = 0L; // 总点数 for (IntWritable val : values) { totalCount++; if (key.get() == 1) { countInsideCircle++; } } double piEstimate = 4.0 * countInsideCircle / totalCount; context.write(new IntWritable(1), new DoubleWritable(piEstimate)); } } public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); Job job = Job.getInstance(conf, "Monte Carlo Pi"); job.setJarByClass(MonteCarloPi.class); job.setMapperClass(PiMapper.class); job.setReducerClass(PiReducer.class); job.setOutputKeyClass(IntWritable.class); job.setOutputValueClass(DoubleWritable.class); FileInputFormat.addInputPath(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); System.exit(job.waitForCompletion(true) ? 0 : 1); } } ``` --- #### 关键点说明 1. **Mapper 的作用** 每个 Mapper 会生成一定数量的随机点,并将其分类标记为“在圆内”或“不在圆内”。这种简单而高效的逻辑非常适合分布式环境下的并行化处理[^4]。 2. **Reducer 的职责** Reducer 接收所有 Mapper 发送的数据流,统计全局范围内符合条件的点占比,进而推导出 π 的估计值。 3. **驱动部分的功能** 它主要用来配置整个 MapReduce 作业的各项属性,包括但不限于指定自定义 Mapper/Reducer 类型、设定输入输出路径等等。 --- #### 提交任务到 YARN 平台 当完成上述编码之后,还需要借助命令行工具将编译好的 jar 包提交给 Hadoop 集群运行。基本流程如下所示: 1. 准备好输入目录(尽管本案例无需真实数据源,仍需创建占位符文件夹) ```bash hdfs dfs -mkdir -p /input/pi_estimation ``` 2. 构建项目并将打包后的 JAR 文件上传至目标位置; ```bash mvn clean package hadoop fs -put target/MonteCarloPi.jar / ``` 3. 提交作业请求 ```bash hadoop jar MonteCarloPi.jar com.example.MonteCarloPi /input/pi_estimation /output/pi_result ``` 随后可以在 YARN Web UI 页面观察任务进度状态[^3]。 --- ### 注意事项 - 数据倾斜问题:理论上每个 Mapper 应均匀分配工作负载,但如果某些分区异常繁忙可能导致整体效率下降。 - 参数调整建议:适当增大迭代次数或者单次试验规模有助于获取更精确的结果。 - 错误排查技巧:熟悉日志查看方式以便快速定位潜在错误源头。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值