前面已经介绍过rabbitmq的安装(一)及rabbitmq的php的扩展安装(二),完成这些安装后,我们就可以开始rabbitmq之旅了。
首先写两个脚本文件,一个生产者脚本(test_publisher.php),一个消费者脚本(test_consumer.php)
生产者脚本(test_publisher.php),用于循环往rabbitmq中发送数据,(可以选择是发送持久化数据或非持久化数据,在性能与数据安全中择决)
消费者脚本(test_consumer.php),用作后台运行,用于从rabbitmq中取数据。
掌握了这两个文件,就可以使用rabbitmq存取数据了,至于存什么样的数据、取出数据后该如何用,这个就是你自身项目的要求来定了。
关于rabbitmq配制参数,一般默认就够用了,当然你也可以根据自身要求进行修改。本篇不详细介绍,到google或官网看吧。
OK,上代码了
nohup命令的用途:使程序在后台(进程)不挂断地运行,像守护进程一样。使用 jobs 查看所有任务
生产者脚本(test_publisher.php)(运行命令:php test_publisher.php 1 / nohup php test_publisher.php 1 &)
- <?php
- error_reporting(E_ERROR);
- ini_set('display_errors','Off');
- declare(ticks = 1);
- $app = 'daemon';
- // Bootstrap the application
- require realpath(dirname(__FILE__)) .'/../../../daemon/bootstrap.php';
- if(empty($_SERVER['argv'][1])){
- echo 'use action start or stop'.PHP_EOL;
- exit;
- }
- $log = $_SERVER['argv'][1];
- $config = array(
- 'host' => '127.0.0.1',
- 'port' => '5672',
- 'login' => 'guest',
- 'password' => 'guest',
- 'vhost'=>'/'
- );
- $j=0;
- while ( true )
- {
- if($j==0)
- {
- // 非持久化
- //$rabbit = new Publisher($config, "bleach_analy_ex_{$log}", "test_{$log}", "bleach_analy_rk_{$log}");
- // 持久化
- $rabbit = new Publisher($config, "bleach_analy_ex_{$log}", "test_{$log}", "bleach_analy_rk_{$log}", "direct", true);
- }
- $j++;
- for($i=0;$i<1600;$i++)
- {
- $t = time();
- $distict = rand(1, 2);
- $push = true;
- if($push==true)
- {
- $message = "1|3|{$distict}|";
- $rabbit->send($message, "bleach_analy_rk_$log");
- }
- }
- if($j>=50)
- {
- $rabbit->__destruct();
- $j = 0;
- break;
- }
- sleep(1);
- }
- echo "finish".PHP_EOL;
- ?>
消费者脚本(test_consumer.php) (运行命令:php test_consumer.php 1 / nohup php test_consumer.php 1 &)
- <?php
- error_reporting(E_ERROR);
- ini_set('display_errors','Off');
- declare(ticks = 1);
- $app = 'daemon';
- // Bootstrap the application
- require realpath(dirname(__FILE__)) .'/../../../daemon/bootstrap.php';
- if(empty($_SERVER['argv'][1])){
- echo 'use action start or stop'.PHP_EOL;
- exit;
- }
- $log = $_SERVER['argv'][1];
- $config = array(
- 'host' => '127.0.0.1',
- 'port' => '5672',
- 'login' => 'guest',
- 'password' => 'guest',
- 'vhost'=>'/'
- );
- $rabbit = new Consumer($config, "ex_{$log}", "rk_{$log}", "test_{$log}","direct");
- while ( true )
- {
- try
- {
- $msg = $rabbit->get( true );
- if(!empty($msg)) echo $msg.PHP_EOL;
- $handle=fopen("msg.log", "a");
- fwrite($handle, $msg.PHP_EOL);
- fclose($handle);
- }
- catch (Exception $e)
- {
- $msg = false;
- }
- }
- echo "end",PHP_EOL;
- ?>