注意事项:

1、accept.php消费者代码需要在命令行执行

2、'username'=>'asdf','password'=>'123456' 改成自己的帐号和密码

RabbitMQCommand.php操作类代码

<?php
/*
* amqp协议操作类,可以访问rabbitMQ
* 需先安装php_amqp扩展
*/
class RabbitMQCommand{ public $configs = array();
//交换机名称
public $exchange_name = '';
//队列名称
public $queue_name = '';
//路由名称
public $route_key = '';
/*
* 持久化,默认True
*/
public $durable = True;
/*
* 自动删除
* exchange is deleted when all queues have finished using it
* queue is deleted when last consumer unsubscribes
*
*/
public $autodelete = False;
/*
* 镜像
* 镜像队列,打开后消息会在节点之间复制,有master和slave的概念
*/
public $mirror = False; private $_conn = Null;
private $_exchange = Null;
private $_channel = Null;
private $_queue = Null; /*
* @configs array('host'=>$host,'port'=>5672,'username'=>$username,'password'=>$password,'vhost'=>'/')
*/ public function __construct($configs = array(), $exchange_name = '', $queue_name = '', $route_key = '') {
$this->setConfigs($configs);
$this->exchange_name = $exchange_name;
$this->queue_name = $queue_name;
$this->route_key = $route_key;
} private function setConfigs($configs) {
if (!is_array($configs)) {
throw new Exception('configs is not array');
}
if (!($configs['host'] && $configs['port'] && $configs['username'] && $configs['password'])) {
throw new Exception('configs is empty');
}
if (empty($configs['vhost'])) {
$configs['vhost'] = '/';
}
$configs['login'] = $configs['username'];
unset($configs['username']);
$this->configs = $configs;
} /*
* 设置是否持久化,默认为True
*/ public function setDurable($durable) {
$this->durable = $durable;
} /*
* 设置是否自动删除
*/ public function setAutoDelete($autodelete) {
$this->autodelete = $autodelete;
}
/*
* 设置是否镜像
*/
public function setMirror($mirror) {
$this->mirror = $mirror;
} /*
* 打开amqp连接
*/ private function open() {
if (!$this->_conn) {
try {
$this->_conn = new AMQPConnection($this->configs);
$this->_conn->connect();
$this->initConnection();
} catch (AMQPConnectionException $ex) {
throw new Exception('cannot connection rabbitmq',500);
}
}
} /*
* rabbitmq连接不变
* 重置交换机,队列,路由等配置
*/ public function reset($exchange_name, $queue_name, $route_key) {
$this->exchange_name = $exchange_name;
$this->queue_name = $queue_name;
$this->route_key = $route_key;
$this->initConnection();
} /*
* 初始化rabbit连接的相关配置
*/ private function initConnection() {
if (empty($this->exchange_name) || empty($this->queue_name) || empty($this->route_key)) {
throw new Exception('rabbitmq exchange_name or queue_name or route_key is empty',500);
}
$this->_channel = new AMQPChannel($this->_conn);
$this->_exchange = new AMQPExchange($this->_channel);
$this->_exchange->setName($this->exchange_name); $this->_exchange->setType(AMQP_EX_TYPE_DIRECT);
if ($this->durable)
$this->_exchange->setFlags(AMQP_DURABLE);
if ($this->autodelete)
$this->_exchange->setFlags(AMQP_AUTODELETE);
$this->_exchange->declare(); $this->_queue = new AMQPQueue($this->_channel);
$this->_queue->setName($this->queue_name);
if ($this->durable)
$this->_queue->setFlags(AMQP_DURABLE);
if ($this->autodelete)
$this->_queue->setFlags(AMQP_AUTODELETE);
if ($this->mirror)
$this->_queue->setArgument('x-ha-policy', 'all');
$this->_queue->declare(); $this->_queue->bind($this->exchange_name, $this->route_key);
} public function close() {
if ($this->_conn) {
$this->_conn->disconnect();
}
} public function __sleep() {
$this->close();
return array_keys(get_object_vars($this));
} public function __destruct() {
$this->close();
} /*
* 生产者发送消息
*/
public function send($msg) {
$this->open();
if(is_array($msg)){
$msg = json_encode($msg);
}else{
$msg = trim(strval($msg));
}
return $this->_exchange->publish($msg, $this->route_key);
}
/*
* 消费者
* $fun_name = array($classobj,$function) or function name string
* $autoack 是否自动应答
*
* function processMessage($envelope, $queue) {
$msg = $envelope->getBody();
echo $msg."\n"; //处理消息
$queue->ack($envelope->getDeliveryTag());//手动应答
}
*/
public function run($fun_name, $autoack = True){
$this->open();
if (!$fun_name || !$this->_queue) return False;
while(True){
if ($autoack) $this->_queue->consume($fun_name, AMQP_AUTOACK);
else $this->_queue->consume($fun_name);
}
} }

  

send.php生产者代码

<?php
set_time_limit(0);
include_once('RabbitMQCommand.php');

$configs = array('host'=>'127.0.0.1','port'=>5672,'username'=>'asdf','password'=>'123456','vhost'=>'/');
$exchange_name = 'class-e-1';
$queue_name = 'class-q-1';
$route_key = 'class-r-1';
$ra = new RabbitMQCommand($configs,$exchange_name,$queue_name,$route_key);
for($i=0;$i<=100;$i++){
$ra->send(date('Y-m-d H:i:s',time()));
}
exit();

  消费者代码

<?php
error_reporting(0);
include_once('RabbitMQCommand.php'); $configs = array('host'=>'127.0.0.1','port'=>5672,'username'=>'asdf','password'=>'123456','vhost'=>'/');
$exchange_name = 'class-e-1';
$queue_name = 'class-q-1';
$route_key = 'class-r-1';
$ra = new RabbitMQCommand($configs,$exchange_name,$queue_name,$route_key); class A{
function processMessage($envelope, $queue) {
$msg = $envelope->getBody();
$envelopeID = $envelope->getDeliveryTag();
$pid = posix_getpid();
file_put_contents("log{$pid}.log", $msg.'|'.$envelopeID.''."\r\n",FILE_APPEND);
$queue->ack($envelopeID);
}
}
$a = new A(); $s = $ra->run(array($a,'processMessage'),false);

  

php rabbitmq操作类及生产者和消费者实例代码 转的更多相关文章

  1. RabbitMQ连接池、生产者、消费者实例

    1.本文分享RabbitMQ的工具类,经过实际项目长期测试,在此分享给发家,各位大神有什么建议请指正 !!! 2.下面是链接池主要代码: import java.util.HashMap; impor ...

  2. Kafka 生产者和消费者入门代码基础

    这篇博文讲解Kafka 的生产者和消费者实例. 基础版本一 生产者 ProducerFastStart.java package com.xingyun.tutorial_1; import org. ...

  3. RabbitMQ简单Java示例——生产者和消费者

    添加Maven依赖: 使用rabbitmq-client的最新Maven坐标: <!-- https://mvnrepository.com/artifact/com.rabbitmq/amqp ...

  4. Linux 进程间通信(包含一个经典的生产者消费者实例代码)

    前言:编写多进程程序时,有时不可避免的需要在多个进程之间传递数据,我们知道,进程的用户的地址空间是独立,父进程中对数据的修改并不会反映到子进程中,但内核是共享的,大多数进程间通信方式都是在内核中建立一 ...

  5. Java中的生产者和消费者实例(多线程 等待唤醒机制)

    1.什么是等待唤醒 我们实现的效果 创建生产者和消费者  对服装进行生产  和售卖 实现生产一个就消费一个 来观察线程的各种状态 下面是用到的方法: wait()方法:让一个线程进行等待 另外一个线程 ...

  6. 一个基于PDO的数据库操作类(新) 一个PDO事务实例

    <?php /* * 作者:胡睿 * 日期:2011/03/19 * 电邮:hooray0905@foxmail.com * * 20110319 * 常用数据库操作,如:增删改查,获取单条记录 ...

  7. 2.NetDh框架之简单高效的日志操作类(附源码和示例代码)

    前言 NetDh框架适用于C/S.B/S的服务端框架,可用于项目开发和学习.目前包含以下四个模块 1.数据库操作层封装Dapper,支持多种数据库类型.多库实例,简单强大: 此部分具体说明可参考博客: ...

  8. Rabbitmq 消息对列 生产者与消费者的具体实现 springboot

    RabbitMQ 基本介绍 RabbitMQ的设计理念是.只要有接收消息的队列. 邮件就会存放到队列里. 直到订阅人取走. . 如果没有可以接收这个消息的消息队列. 默认是抛弃这个消息的.. 我实现的 ...

  9. RabbitMQ的使用(五)RabbitMQ Java Client简单生产者、消费者代码示例

    pom文件: <dependencies> <dependency> <groupId>com.rabbitmq</groupId> <artif ...

随机推荐

  1. Vue.js-this详解

    this this 指向并不是在函数定义的时候确定的,而是在调用的时候确定的.换句话说,函数的调用方式(直接调用.方法调用.new调用.bind.call.apply.箭头函数)决定了 this 指向 ...

  2. 怎么在WEBSTORM中设置代码模板 Live Templates

    怎么在WEBSTORM中设置代码模板 Live Templates setting 里面 https://www.cnblogs.com/xinzaimengzai/p/9938464.html

  3. 使用Timer组件制作计时器

    实现效果: 知识运用: Timer组件的interval属性 //获取或设置Timer组件Tick事件发生的时间间隔 public int Interval {get;set} NumericUpDo ...

  4. ubuntu下安装eclipse<转>

    转载自http://my.oschina.net/u/1407116/blog/227084      http://my.oschina.net/u/1407116/blog/227087 一 JD ...

  5. CPP-基础:c++读取ini文件

    配置文件格式是[JP]K=2EC156673E 2F4240 5595F6 char str[50];GetPrivateProfileString("JP", "K&q ...

  6. WINDOWS-API:关于线程CreateThread,_beginthead(_beginthreadex),AfxBeginThread

    [转]windows多线程编程CreateThread,_beginthead(_beginthreadex)和AfxBeginThread的区别 在Windows的多线程编程中,创建线程的函数主要有 ...

  7. DROP OPERATOR - 删除一个操作符

    SYNOPSIS DROP OPERATOR name ( lefttype | NONE , righttype | NONE ) [ CASCADE | RESTRICT ] DESCRIPTIO ...

  8. Bootstrap历练实例:导航内的下拉菜单

    <!DOCTYPE html><html><head><meta http-equiv="Content-Type" content=&q ...

  9. MySql下最好用的数据库管理工具是哪个

    MySql下最好用的数据库管理工具是哪个? 维基上有个很全的列表: https://en.wikipedia.org/wiki/Comparison_of_database_tools   1. ph ...

  10. 使用max函数计算EXCEL个税公式

    1.Max()函数是求括号内的数的最大值.2.其中,第一和第二个大括号{}内的数,相信作为财务的应该很清楚,就是个人所得税的缴税比例,以及速算个人应缴所得税的相关数据.3.在EXCEL中,使用{}表示 ...