在 hadoop 1.2.1成功配置了爲分佈式環境,經過了十一長假,該繼續學習了,
這次要在eclipse下運行一個hadoop 應用
開發環境
操作系統:CentOS Linux release 6.0 (Final)
eclipse4.3
java version "1.7.0_25"
第一步 運行 start-all.sh 可以參照上一篇文章,啓動守護線程
發現啓動有問題,原來是ip地址衝突了而我的xml配置中設置的ip地址沒有生效,沒辦法改一下ip
DEVICE="eth0"
BOOTPROTO=static
IPADDR=192.168.2.88
此處改成沒有被佔用的ip
/etc/rc.d/init.d/network restart 使修改生效
生效後修改vim core-site.xml
vim mapred-site.xml 設置的ip (如果設置成 localhost 就不用改了)
配置eclipse插件
獲取插件
參考:http://f.dataguru.cn/thread-187770-1-1.html 可以自己生成 也可以直接下載使用
安裝完重新打開eclipse後
在showview裏面可以考到選項如果
選擇讓其顯示在控制檯旁邊
右鍵新建一個
如圖
master 處填寫 mapred-site.xml ip和端口 dfs master 處填寫 core-site.xml ip和端口
設置hadoop的安裝路徑 如圖
設置完後可以看到 資源目錄下如圖
我們可以在這裏通過右鍵對dfs文件進行操作 (增刪 上傳 下載)
創建helloword工程
File -> New -> Project 選擇“Map/Reduce Project”,然後輸入項目名稱,創建項目。插件會自動把hadoop根目錄和lib目錄下的所有jar包導入
如圖
第一個例子準備運行文檔中的實例
打開http://hadoop.apache.org/docs/r1.2.1/mapred_tutorial.html
點擊如圖
按照例子 建立package 和 class 將代碼複製
package org.myorg; 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<LongWritable, Text, Text, IntWritable> { private final static IntWritable one = new IntWritable(1); private Text word = new Text(); public void map(LongWritable key, Text value, OutputCollector<Text, IntWritable> 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<Text, IntWritable, Text, IntWritable> { public void reduce(Text key, Iterator<IntWritable> values, OutputCollector<Text, IntWritable> 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); } }
直接運行會報錯 報錯了 (需要兩個參數) 參考文檔
需要傳入 輸入目錄 和 輸出目錄
可以根據根據DFS 中的目錄 進行設置 也可以直接寫 絕對目錄 如圖
點擊運行成功
通過
hadoop dfs -cat /home/hadoop-1.2.1/output/part-00000 可以查看輸出 也可以在eclipse中dfs目錄進行查看