首頁 後端開發 php教程 php讯息队列

php讯息队列

Jun 13, 2016 am 10:49 AM
gt message msg queue this

php消息队列

php-通过共享内存实现消息队列和进程通信的两个类

实现消息队列,可以使用比较专业的工具,例如:Apache ActiveMQ、memcacheq…..,下面是两个基本简单的实现方式:

使用memcache方法来实现

<?php /* * @Copyright (c) 2007,上海友邻信息科技有限公司 * @All	rights reserved. * * 这个消息队列不是线程安全的,我只是尽量的避免了冲突的可能性。如果你要实现线程安全的,一个建议是通过文件进行锁定,然后进行操作。 * * @filename   MemcacheQueue.class.php *//** * Class and Function List: * Function list: * - __construct() * - singleton() * - init() * - __get() * - __set() * - isEmpty() * - isFull() * - enQueue() * - deQueue() * - getTop() * - getAll() * - getPage() * - makeEmpty() * - getAllKeys() * - add() * - increment() * - decrement() * - set() * - get() * - delete() * - getKeyByPos() * Classes list: * - Yl_MemcacheQueue */class Yl_MemcacheQueue {	private static $instance;	private $memcache;	private $name;	private $prefix;	private $maxSize;		private function __construct() {	}		static function singleton() {				if (! (self::$instance instanceof self)) {			self::$instance = new Yl_MemcacheQueue ();				}				return self::$instance;	}		public function init($max_size, $name, $prefix = "__queue__") {		$max_size = 1000;		$name = '_war_';		$prefix = '_queue';				$this->memcache = Yl_Memcache::singleton ();		$this->name = $name;		$this->prefix = $prefix;		$this->maxSize = $max_size;				$this->add ( 'front', 0 );		$this->add ( 'rear', 0 );		$this->add ( 'size', 0 );	}		function isEmpty() {		return $this->get ( 'size' ) == 0;	}		function isFull() {		return $this->get ( 'size' ) >= $this->maxSize;	}		function enQueue($data) {		if ($this->isFull ()) {			throw new Exception ( "Queue is Full" );		}				$size = $this->increment ( 'size' );		$rear = $this->increment ( 'rear' );				$this->set ( ($rear - 1) % $this->maxSize, $data );				return $this;	}		function deQueue() {		if ($this->isEmpty ()) {			throw new Exception ( "Queue is Empty" );		}				$this->decrement ( 'size' );		$front = $this->increment ( 'front' );		$this->delete ( ($front - 1) % $this->maxSize );				return $this;	}		function getTop() {		return $this->get ( $this->get ( 'front' ) % $this->maxSize );	}		function getAll() {		return $this->getPage ();	}		function getPage($offset = 0, $limit = 0) {		$size = $this->get ( 'size' );				if (0 == $size || $size get ( 'front' ) % $this->maxSize;		$rear = $this->get ( 'rear' ) % $this->maxSize;				$keys [] = $this->getKeyByPos ( ($front + $offset) % $this->maxSize );		$num = 1;				for($pos = ($front + $offset + 1) % $this->maxSize; $pos != $rear; $pos = ($pos + 1) % $this->maxSize) {			$keys [] = $this->getKeyByPos ( $pos );			$num ++;						if ($limit > 0 && $limit == $num) {				break;			}		}				return array_values ( $this->memcache->get ( $keys ) );	}		function makeEmpty() {		$keys = $this->getAllKeys ();				foreach ( $keys as $value ) {			$this->delete ( $value );		}				$this->delete ( "rear" );		$this->delete ( "front" );		$this->delete ( 'size' );		$this->delete ( "maxSize" );	}		private function getAllKeys() {		if ($this->isEmpty ()) {			return array ();		}				$keys [] = $this->get ( 'front' );				for($pos = ($this->get ( 'front' ) % $this->maxSize + 1) % $this->maxSize; $pos != $this->get ( 'rear' ) % $this->maxSize; $pos = ($pos + 1) % $this->maxSize) {			$keys [] = $pos;		}				return $keys;	}		private function add($pos, $data) {		$this->memcache->add ( $this->getKeyByPos ( $pos ), $data );				return $this;	}		private function increment($pos) {				return $this->memcache->increment ( $this->getKeyByPos ( $pos ) );	}		private function decrement($pos) {		$this->memcache->decrement ( $this->getKeyByPos ( $pos ) );	}		private function set($pos, $data) {		$this->memcache->save ( $data, $this->getKeyByPos ( $pos ) );				return $this;	}		private function get($pos) {				return $this->memcache->get ( $this->getKeyByPos ( $pos ) );	}		private function delete($pos) {				return $this->memcache->delete ( $this->getKeyByPos ( $pos ) );	}		private function getKeyByPos($pos) {				return $this->prefix . $this->name . $pos;	}}?>
登入後複製
使用共享内存队列实现 点击查看原文地址

?

利用PHP操作Linux消息队列完成进程间通信

当我们开发的系统需要使用多进程方式运行时,进程间通信便成了至关重要的环节。消息队列(message queue)是Linux系统进程间通信的一种方式。
  关于Linux系统进程通信的概念及实现可查看:http://www.ibm.com/developerworks/cn/linux/l-ipc/
  关于Linux系统消息队列的概念及实现可查看:http://www.ibm.com/developerworks/cn/linux/l-ipc/part4/
  PHP的sysvmsg模块是对Linux系统支持的System V IPC中的System V消息队列函数族的封装。我们需要利用sysvmsg模块提供的函数来进进程间通信。先来看一段示例代码_1:

<?php $message_queue_key = ftok(__FILE__, 'a');$message_queue = msg_get_queue($message_queue_key, 0666);var_dump($message_queue);$message_queue_status = msg_stat_queue($message_queue);print_r($message_queue_status);//向消息队列中写msg_send($message_queue, 1, "Hello,World!");$message_queue_status = msg_stat_queue($message_queue);print_r($message_queue_status);//从消息队列中读msg_receive($message_queue, 0, $message_type, 1024, $message, true, MSG_IPC_NOWAIT);print_r($message."\r\n");msg_remove_queue($message_queue);?>
登入後複製
?这段代码的运行结果如下:
resource(4) of type (sysvmsg queue)Array(    [msg_perm.uid] => 1000    [msg_perm.gid] => 1000    [msg_perm.mode] => 438    [msg_stime] => 0    [msg_rtime] => 0    [msg_ctime] => 1279849495    [msg_qnum] => 0    [msg_qbytes] => 16384    [msg_lspid] => 0    [msg_lrpid] => 0)Array(    [msg_perm.uid] => 1000    [msg_perm.gid] => 1000    [msg_perm.mode] => 438    [msg_stime] => 1279849495    [msg_rtime] => 0    [msg_ctime] => 1279849495    [msg_qnum] => 1    [msg_qbytes] => 16384    [msg_lspid] => 2184    [msg_lrpid] => 0)Hello,World!
登入後複製
?可以看到已成功从消息队列中读取“Hello,World!”字符串

下面列举一下示例代码中的主要函数:

ftok ( string $pathname , string $proj ) 	手册上给出的解释是:Convert a pathname and a project identifier to a System V IPC key。这个函数返回的键值唯一对应linux系统中一个消息队列。在获得消息队列的引用之前都需要调用这个函数。msg_get_queue ( int $key [, int $perms ] )	msg_get_queue()会根据传入的键值返回一个消息队列的引用。如果linux系统中没有消息队列与键值对应,msg_get_queue()将会创建一个新的消息队列。函数的第二个参数需要传入一个int值,作为新创建的消息队列的权限值,默认为0666。这个权限值与linux命令chmod中使用的数值是同一个意思,因为在linux系统中一切皆是文件。msg_send ( resource $queue , int $msgtype , mixed $message [, bool $serialize [, bool $blocking [, int &$errorcode ]]] )	顾名思义,该函数用来向消息队列中写数据。msg_stat_queue ( resource $queue ) 	这个函数会返回消息队列的元数据。消息队列元数据中的信息很完整,包括了消息队列中待读取的消息数、最后读写队列的进程ID等。示例代码在第8行调用该函数返回的数组中队列中待读取的消息数msg_qnum值为0。msg_receive ( resource $queue , int $desiredmsgtype , int &$msgtype , int $maxsize , mixed &$message [, bool $unserialize [, int $flags [, int &$errorcode ]]] ) 	msg_receive用于读取消息队列中的数据。msg_remove_queue ( resource $queue )     msg_remove_queue用于销毁一个队列。
登入後複製
?示例代码_1只是展示了PHP操作消息队列函数的应用。下面的代码具体描述了进程间通信的场景
<?php $message_queue_key = ftok ( __FILE__, 'a' );$message_queue = msg_get_queue ( $message_queue_key, 0666 );$pids = array ();for($i = 0; $i < 5; $i ++) {	//创建子进程	$pids [$i] = pcntl_fork ();		if ($pids [$i]) {		echo "No.$i child process was created, the pid is $pids[$i]\r\n";	} elseif ($pids [$i] == 0) {		$pid = posix_getpid ();		echo "process.$pid is writing now\r\n";				msg_send ( $message_queue, 1, "this is process.$pid's data\r\n" );		posix_kill ( $pid, SIGTERM );	}}do {	msg_receive ( $message_queue, 0, $message_type, 1024, $message, true, MSG_IPC_NOWAIT );	echo $message;	//需要判断队列是否为空,如果为空就退出//break;} while ( true )?>
登入後複製
运行结果为:
No.0 child process was created, the pid is 5249No.1 child process was created, the pid is 5250No.2 child process was created, the pid is 5251No.3 child process was created, the pid is 5252No.4 child process was created, the pid is 5253process.5251 is writing nowthis is process.5251's dataprocess.5253 is writing nowprocess.5252 is writing nowprocess.5250 is writing nowthis is process.5253's datathis is process.5252's datathis is process.5250's dataprocess.5249 is writing nowthis is process.5249's data
登入後複製

redis
http://www.neatstudio.com/show-976-1.shtml

?

php自带的三个消息队列相关的函数
http://www.zhangguangda.com/?p=89?

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

<🎜>:泡泡膠模擬器無窮大 - 如何獲取和使用皇家鑰匙
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora:巫婆樹的耳語 - 如何解鎖抓鉤
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
北端:融合系統,解釋
3 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Java教學
1668
14
CakePHP 教程
1426
52
Laravel 教程
1329
25
PHP教程
1273
29
C# 教程
1256
24
華為GT3 Pro和GT4的差異是什麼? 華為GT3 Pro和GT4的差異是什麼? Dec 29, 2023 pm 02:27 PM

許多用戶在選擇智慧型手錶的時候都會選擇的華為的品牌,其中華為GT3pro和GT4都是非常熱門的選擇,不少用戶都很好奇華為GT3pro和GT4有什麼區別,下面就給大家介紹一下二者。華為GT3pro和GT4有什麼差別一、外觀GT4:46mm和41mm,材質是玻璃鏡板+不鏽鋼機身+高分纖維後殼。 GT3pro:46.6mm和42.9mm,材質是藍寶石玻璃鏡+鈦金屬機身/陶瓷機身+陶瓷後殼二、健康GT4:採用最新的華為Truseen5.5+演算法,結果會更加的精準。 GT3pro:多了ECG心電圖和血管及安

Laravel開發:如何使用Laravel Queue處理非同步任務? Laravel開發:如何使用Laravel Queue處理非同步任務? Jun 13, 2023 pm 08:32 PM

隨著應用程式變得越來越複雜,處理和管理大量資料和流程是一個挑戰。為了處理這種情況,Laravel為使用者提供了一個非常強大的工具,即Laravel隊列(Queue)。它允許開發人員在後台運行諸如發送電子郵件,生成PDF,處理影像剪裁等任務,而不會對使用者介面產生任何影響。在這篇文章中,我們將深入研究如何使用Laravel隊列。什麼是LaravelQueue隊列

修復:截圖工具在 Windows 11 中不起作用 修復:截圖工具在 Windows 11 中不起作用 Aug 24, 2023 am 09:48 AM

為什麼截圖工具在Windows11上不起作用了解問題的根本原因有助於找到正確的解決方案。以下是截圖工具可能無法正常工作的主要原因:對焦助手已開啟:這可以防止截圖工具開啟。應用程式損壞:如果截圖工具在啟動時崩潰,則可能已損壞。過時的圖形驅動程式:不相容的驅動程式可能會幹擾截圖工具。來自其他應用程式的干擾:其他正在運行的應用程式可能與截圖工具衝突。憑證已過期:升級過程中的錯誤可能會導致此issu簡單的解決方案這些適合大多數用戶,不需要任何特殊的技術知識。 1.更新視窗與Microsoft應用程式商店應用程

vue3中怎麼使用element-plus呼叫message vue3中怎麼使用element-plus呼叫message May 17, 2023 pm 03:52 PM

vue3使用element-plus呼叫message環境:vue3+typescript+element-plus1.全局引入element之後element已經在app.config.globalProperties添加了全局方法$message所以在optionsAPI中可以直接使用mounted(){(thisasany). $message.success("this.$message");}2.在CompositionAPI中setup方法傳入了兩個變數props和

多執行緒環境下Java Queue佇列的安全性問題及解決方案 多執行緒環境下Java Queue佇列的安全性問題及解決方案 Jan 13, 2024 pm 03:04 PM

JavaQueue佇列在多執行緒環境下的安全性問題與解決方案引言:在多執行緒程式設計中,程式中的共享資源可能面臨競爭條件,這可能導致資料的不一致性或錯誤。在Java中,Queue佇列是一種常用的資料結構,在多個執行緒同時操作佇列的情況下,就存在安全性問題。本文將討論JavaQueue佇列在多執行緒環境下的安全性問題,並介紹幾個解決方案,重點以程式碼範例的方式解釋。一

如何修復無法連線到iPhone上的App Store錯誤 如何修復無法連線到iPhone上的App Store錯誤 Jul 29, 2023 am 08:22 AM

第1部分:初始故障排除步驟檢查蘋果的系統狀態:在深入研究複雜的解決方案之前,讓我們先從基礎知識開始。問題可能不在於您的設備;蘋果的伺服器可能會關閉。造訪Apple的系統狀態頁面,查看AppStore是否正常運作。如果有問題,您所能做的就是等待Apple修復它。檢查您的網路連接:確保您擁有穩定的網路連接,因為「無法連接到AppStore」問題有時可歸因於連接不良。嘗試在Wi-Fi和行動數據之間切換或重置網路設定(「常規」>「重置」>「重置網路設定」>設定)。更新您的iOS版本:

php提交表单通过后,弹出的对话框怎样在当前页弹出,该如何解决 php提交表单通过后,弹出的对话框怎样在当前页弹出,该如何解决 Jun 13, 2016 am 10:23 AM

php提交表单通过后,弹出的对话框怎样在当前页弹出php提交表单通过后,弹出的对话框怎样在当前页弹出而不是在空白页弹出?想实现这样的效果:而不是空白页弹出:------解决方案--------------------如果你的验证用PHP在后端,那么就用Ajax;仅供参考:HTML code

聊聊Vue2為什麼能透過this存取各種選項中屬性 聊聊Vue2為什麼能透過this存取各種選項中屬性 Dec 08, 2022 pm 08:22 PM

這篇文章帶大家解讀vue原始碼,來介紹一下Vue2中為什麼可以使用 this 存取各種選項中的屬性,希望對大家有幫助!

See all articles