PHP+RabbitMQ实现消息队列的完整代码
时间:2022-07-27
本文章向大家介绍PHP+RabbitMQ实现消息队列的完整代码,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
前言
为什么使用RabbitMq而不是ActiveMq或者RocketMq?
首先,从业务上来讲,我并不要求消息的100%接受率,并且,我需要结合php开发,RabbitMq相较RocketMq,延迟较低(微妙级)。至于ActiveMq,貌似问题较多。RabbitMq对各种语言的支持较好,所以选择RabbitMq。
先安装PHP对应的RabbitMQ,这里用的是 php_amqp 不同的扩展实现方式会有细微的差异.
php扩展地址: http://pecl.php.net/package/amqp
具体以官网为准 http://www.rabbitmq.com/getstarted.html
介绍
- config.php 配置信息
- BaseMQ.php MQ基类
- ProductMQ.php 生产者类
- ConsumerMQ.php 消费者类
- Consumer2MQ.php 消费者2(可有多个)
config.php
<?php
return [
//配置
'host' = [
'host' = '127.0.0.1',
'port' = '5672',
'login' = 'guest',
'password' = 'guest',
'vhost'= '/',
],
//交换机
'exchange'= 'word',
//路由
'routes' = [],
];
BaseMQ.php
<?php
/**
* Created by PhpStorm.
* User: pc
* Date: 2018/12/13
* Time: 14:11
*/
namespace MyObjSummaryrabbitMQ;
/** Member
* AMQPChannel
* AMQPConnection
* AMQPEnvelope
* AMQPExchange
* AMQPQueue
* Class BaseMQ
* @package MyObjSummaryrabbitMQ
*/
class BaseMQ
{
/** MQ Channel
* @var AMQPChannel
*/
public $AMQPChannel ;
/** MQ Link
* @var AMQPConnection
*/
public $AMQPConnection ;
/** MQ Envelope
* @var AMQPEnvelope
*/
public $AMQPEnvelope ;
/** MQ Exchange
* @var AMQPExchange
*/
public $AMQPExchange ;
/** MQ Queue
* @var AMQPQueue
*/
public $AMQPQueue ;
/** conf
* @var
*/
public $conf ;
/** exchange
* @var
*/
public $exchange ;
/** link
* BaseMQ constructor.
* @throws AMQPConnectionException
*/
public function __construct()
{
$conf = require 'config.php' ;
if(!$conf)
throw new AMQPConnectionException('config error!');
$this- conf = $conf['host'] ;
$this- exchange = $conf['exchange'] ;
$this- AMQPConnection = new AMQPConnection($this- conf);
if (!$this- AMQPConnection- connect())
throw new AMQPConnectionException("Cannot connect to the broker!n");
}
/**
* close link
*/
public function close()
{
$this- AMQPConnection- disconnect();
}
/** Channel
* @return AMQPChannel
* @throws AMQPConnectionException
*/
public function channel()
{
if(!$this- AMQPChannel) {
$this- AMQPChannel = new AMQPChannel($this- AMQPConnection);
}
return $this- AMQPChannel;
}
/** Exchange
* @return AMQPExchange
* @throws AMQPConnectionException
* @throws AMQPExchangeException
*/
public function exchange()
{
if(!$this- AMQPExchange) {
$this- AMQPExchange = new AMQPExchange($this- channel());
$this- AMQPExchange- setName($this- exchange);
}
return $this- AMQPExchange ;
}
/** queue
* @return AMQPQueue
* @throws AMQPConnectionException
* @throws AMQPQueueException
*/
public function queue()
{
if(!$this- AMQPQueue) {
$this- AMQPQueue = new AMQPQueue($this- channel());
}
return $this- AMQPQueue ;
}
/** Envelope
* @return AMQPEnvelope
*/
public function envelope()
{
if(!$this- AMQPEnvelope) {
$this- AMQPEnvelope = new AMQPEnvelope();
}
return $this- AMQPEnvelope;
}
}
ProductMQ.php
<?php
//生产者 P
namespace MyObjSummaryrabbitMQ;
require 'BaseMQ.php';
class ProductMQ extends BaseMQ
{
private $routes = ['hello','word']; //路由key
/**
* ProductMQ constructor.
* @throws AMQPConnectionException
*/
public function __construct()
{
parent::__construct();
}
/** 只控制发送成功 不接受消费者是否收到
* @throws AMQPChannelException
* @throws AMQPConnectionException
* @throws AMQPExchangeException
*/
public function run()
{
//频道
$channel = $this- channel();
//创建交换机对象
$ex = $this- exchange();
//消息内容
$message = 'product message '.rand(1,99999);
//开始事务
$channel- startTransaction();
$sendEd = true ;
foreach ($this- routes as $route) {
$sendEd = $ex- publish($message, $route) ;
echo "Send Message:".$sendEd."n";
}
if(!$sendEd) {
$channel- rollbackTransaction();
}
$channel- commitTransaction(); //提交事务
$this- close();
die ;
}
}
try{
(new ProductMQ())- run();
}catch (Exception $exception){
var_dump($exception- getMessage()) ;
}
ConsumerMQ.php
<?php
//消费者 C
namespace MyObjSummaryrabbitMQ;
require 'BaseMQ.php';
class ConsumerMQ extends BaseMQ
{
private $q_name = 'hello'; //队列名
private $route = 'hello'; //路由key
/**
* ConsumerMQ constructor.
* @throws AMQPConnectionException
*/
public function __construct()
{
parent::__construct();
}
/** 接受消息 如果终止 重连时会有消息
* @throws AMQPChannelException
* @throws AMQPConnectionException
* @throws AMQPExchangeException
* @throws AMQPQueueException
*/
public function run()
{
//创建交换机
$ex = $this- exchange();
$ex- setType(AMQP_EX_TYPE_DIRECT); //direct类型
$ex- setFlags(AMQP_DURABLE); //持久化
//echo "Exchange Status:".$ex- declare()."n";
//创建队列
$q = $this- queue();
//var_dump($q- declare());exit();
$q- setName($this- q_name);
$q- setFlags(AMQP_DURABLE); //持久化
//echo "Message Total:".$q- declareQueue()."n";
//绑定交换机与队列,并指定路由键
echo 'Queue Bind: '.$q- bind($this- exchange, $this- route)."n";
//阻塞模式接收消息
echo "Message:n";
while(True){
$q- consume(function ($envelope,$queue){
$msg = $envelope- getBody();
echo $msg."n"; //处理消息
$queue- ack($envelope- getDeliveryTag()); //手动发送ACK应答
});
//$q- consume('processMessage', AMQP_AUTOACK); //自动ACK应答
}
$this- close();
}
}
try{
(new ConsumerMQ)- run();
}catch (Exception $exception){
var_dump($exception- getMessage()) ;
}
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对ZaLou.Cn的支持。
- WP_Widget_PostViews has a deprecated constructor 报错解决
- 详解Linux系统的CPU负载均值
- Linux服务器的进程查看命令详解
- 另类SEO分享:利用JS封装iframe躲过搜索引擎的抓取
- Linux :MAC 地址克隆方法
- 解决WordPress修改数据库表前缀后无法登陆的问题
- 解决启用WP-Super-Cache后出现的几个问题
- Shell下制作自解压安装包,实现脚本的简单加密
- WordPress(Twenty Ten主题)文章副标题修改教程
- ipvsadm启动报错解决办法,另附ipvsadm详细参数
- Linux:mv 命令的10个实用例子
- Linux优化方法收集与整理
- 常用MySQL语句搜集整理
- ASM 翻译系列第十二弹:ASM Internal amdu - ASM Metadata Dump Utility
- php概述
- php教程
- php环境搭建
- PHP书写格式
- php变量
- php常量
- PHP注释
- php数组
- php字符串 string
- PHP整型 integer
- PHP浮点型 float
- php布尔型
- php数据类型之数组
- php数据类型之对象
- php数据类型之null
- php数据类型之间的转换
- php运算符
- php表达式
- PHP循环控制
- PHP流程控制
- php函数
- php全局变量
- PHP魔术变量
- php命名空间
- php 日期
- PHP包含文件
- php文件
- PHP 文件上传
- php Cookies
- php Sessions
- php email
- php安全email
- php错误处理
- PHP异常处理
- php过滤器
- PHP 高级过滤器
- php json
- php 表单
- PHP MySQL 简介
- PHP 连接 MySQL
- php创建数据库
- php 创建表
- php mysq 插入数据
- PHP MySQL 插入多条数据
- PHP MySQL 预处理语句
- php mysql 读取数据
- php mysql where
- PHP MySQL Order By
- PHP MySQL Update
- PHP MySQL Delete
- php ODBC
- MySQL死锁系列-线上死锁问题排查思路
- # 3分钟短文:Laravel路由注册,你必须掌握的“动词”!
- 资深程序员带你解锁Android性能优化五大误区和两大疑点!(附333页性能优化PDF宝典)
- Android大三提前批的钉钉和抖音面筋,阿里挂了HR面,抖音通过收获Offer
- leetcode之键盘行
- 浅析centos 7 自带的 php 5.4升级为 5.6的方法
- Linux内核设备驱动地址映射笔记整理
- Linux中的who命令实例介绍
- Linux十个新手命令分享
- Linux 内核通用链表学习小结
- 从零开始针对 .NET 应用的 DevOps 运营实践 - 运行环境搭建
- 面试问我,创建多少个线程合适?我该怎么说
- C语言链表实例--玩转链表
- 帝国CMS怎么利用灵动标签循环调用多个栏目下的文章
- PHP 加密 Password Hashing API基础知识点