当前位置:网站首页>Redis cache message queue

Redis cache message queue

2022-06-26 04:21:00 Scholar and

//  Message queue class :
// 1: Definition :
//  queue , Team head , A party , Maximum 
// 2: Define methods 
//  Initialize queue , Judge team empty , Judge that the team is full , The team , Out of the team 
// 【 Judge if the team is full , The team is full : Return to wait ; The team is not full : Queued write data to cache queue , And return the success value ;】
// 3: Timing task , Loop handler :
// 【 Judge whether the team is empty , Team space : Don't deal with ; No team empty : Circular queue , Processing data , Write to database , Out of the team , Delete the current queue value ;】
class redisList{
    

	public $redis;
	// Maximum queue length 
	public $max_size;
	// Queue key value 
	public $list_key;
	// Database instance 
	public $db;


	public function __construct(){
    
		// Instantiation redis cache 
		$this->redis    = new Redis();
		$this->redis->pconnect('127.0.0.1', 6379);
		// Queue maximum 
		$this->max_size = 100000;
		$this->list_key = 'list';
		$this->db       = DB::getIntance();
	}

	// Queue request ( Call queue , Fast write cache , And give the return value )
	public function intoQueue($data){
    
		// Current number of queue elements 
		$list_num = $this->redis->lLen( $this->list_key );
		// If the current number of queues , Less than the queue maximum , You are allowed to join the team , Otherwise return to wait or end 
		if ( $list_num <  $this->max_size ) {
    
			// Write data to the end of the queue 
			$this->redis->rPush($this->list_key, $data);
			echo " Team success ";
		} else {
    
			echo ' The queue is full , Please be patient ';
		}
	}


	// Out of the team request 
	public function outQueue() {
    
		// Get the first element of the queue , And delete it from the queue 
		$data   = $this->redis->lPop( $this->list_key );
		$return = $data ? $data : false;
		return $return;
	}

	// Timing task , Business processing 
	public function businessHandle(){
    
		// Current number of queue elements 
		$list_num = $this->redis->lLen( $this->list_key );
		// If the team is empty , Do not perform 
		if ($list_num == 0) {
    
			return false;
		}
		while(1) {
    
		  	try {
    

		    	$data = $this->outQueue();
		    	if ($data) {
    

				    /**  Logic and data processing  */
					// Data processing failed , Re write data to the queue 
					//$this->rPush($this->list_key, $data);
					

				} else {
    
					break;
				}

		  	} catch (Exception $e) {
    
		  		// Record error messages 
		    	echo  $e->getMessage();
		  	}
		}
	}

	public function __destruct(){
    
		$this->redis->close();
	}

}

原网站

版权声明
本文为[Scholar and]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202180533334244.html