使用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文件,写入如下代码:
- #!/usr/local/php/bin/php
- <?php
- $word2count = array();
- // input comes from STDIN
- while (($line = fgets(STDIN)) !== false) {
- // remove leading and trailing whitespace
- $line = trim($line);
- // parse the input we got from mapper.php
- list($word, $count) = explode(chr(9), $line);
- // convert count (currently a string) to int
- $count = intval($count);
- // sum counts
- if ($count > 0) $word2count[$word] += $count;
- }
- // sort the words lexigraphically
- //
- // this set is NOT required, we just do it so that our
- // final output will look more like the official Hadoop
- // word count examples
- ksort($word2count);
- // write the results to STDOUT (standard output)
- foreach ($word2count as $word => $count) {
- echo $word, chr(9), $count, PHP_EOL;
- }
- ?>
这段代码的大意是统计每个单词出现了多少次数,并以”
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
