手机版
你好,游客 登录 注册
背景:
阅读新闻

用PHP写Hadoop的MapReduce程序

[日期:2012-02-17] 来源:Linux社区  作者:hguisu [字体:大 中 小]

使用stdin接收输入

PHP支持多种参数传入的方法,大家最熟悉的应该是从$_GET, $_POST超全局变量里面取通过Web传递的参数,次之是从$_SERVER['argv']里取通过命令行传入的参数,这里,采用的是标准输入stdin

它的使用效果是:

在linux控制台输入 ./mapper.php

wc_mapper.php运行,控制台进入等候用户键盘输入状态

用户通过键盘输入文本

用户按下Ctrl + D终止输入,wc_mapper.php开始执行真正的业务逻辑,并将执行结果输出

那么stdout在哪呢?print本身已经就是stdout啦,跟我们以前写web程序和CLI脚本没有任何不同。

reducer函数

创建reducer.php文件,写入如下代码:

[php]
  1. #!/usr/local/php/bin/php  
  2. <?php  
  3. $word2count = array();  
  4. // input comes from STDIN   
  5. while (($line = fgets(STDIN)) !== false) {  
  6.     // remove leading and trailing whitespace   
  7.     $line = trim($line);  
  8.     // parse the input we got from mapper.php   
  9.     list($word, $count) = explode(chr(9), $line);  
  10.     // convert count (currently a string) to int   
  11.     $count = intval($count);  
  12.     // sum counts   
  13.     if ($count > 0) $word2count[$word] += $count;  
  14. }  
  15. // sort the words lexigraphically   
  16. //   
  17. // this set is NOT required, we just do it so that our   
  18. // final output will look more like the official Hadoop   
  19. // word count examples   
  20. ksort($word2count);  
  21. // write the results to STDOUT (standard output)   
  22. foreach ($word2count as $word => $count) {  
  23.     echo $word, chr(9), $count, PHP_EOL;  
  24. }  
  25. ?>  

这段代码的大意是统计每个单词出现了多少次数,并以”

hello   2

world  1″

这样的形式输出

用Hadoop来运行

把文件放入 Hadoop 的 DFS 中:

bin/hadoop dfs -put test.log test
执行 php 程序处理这些文本(以Streaming方式执行PHP mapreduce程序:):

bin/hadoop jar contrib/streaming/hadoop-streaming-0.20.203.0.jar -mapper /usr/local/hadoop/mapper.php -reducer /usr/local/hadoop/reducer.php -input test/* -output out

注意:

1) input和output目录是在hdfs上的路径

2) mapper和reducer是在本地机器的路径,一定要写绝对路径,不要写相对路径,以免到时候hadoop报错说找不到mapreduce程序

3 ) mapper.php 和 reducer.php 必须复制到所有 DataNode 服务器上的相同路径下, 所有的服务器都已经安装php.且安装路径一样.

查看结果

bin/hadoop d fs -cat /tmp/out/part-00000

linux
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款