redis实现消息队列
简单实现下redis的消息队列
连接redis数据库:
class connectRedis { static $redis_port = '6379'; static $redis_host = '127.0.0.1'; private function __construct() { } static public $instance; static public function getinstance() { if (!self::$instance) self::$instance = new self(); try { $redis = new Redis(); $redis->connect(static::$redis_host, static::$redis_port); } catch (Exception $e) { die('RedisException : Can\'t connect to ' . static::$redis_host . ':' . static::$redis_port); } return $redis; } }
封装队列方法类:
require_once('../connectRedis.php'); class msgQueue { static $redis; public function __construct() { static::$redis = connectRedis::getinstance(); } /* * 查看队列中的当前数据 * @param $dbname 数据库 * @param $key_name key名称 * @return array 返回值 */ public function selectQueue($dbname, $key_name) { static::$redis->select($dbname); static::$redis->auth(''); $list = static::$redis->lrange($key_name, 0, -1); return $list; } /* * 入队 * @param $dbname 数据库 * @param $key_name key名称 * @param $data 入队数据 * @return bool 返回值 */ public function inQueue($dbname, $key_name, $data) { static::$redis->select($dbname); static::$redis->auth(''); $data = json_encode($data); $in = static::$redis->lpush($key_name, $data); if ($in) return true; else return false; } /* * 出队 * @param $dbname 数据库 * @param $key_name key名称 * @return string 返回值 */ public function outQueue($dbname, $key_name) { static::$redis->select($dbname); static::$redis->auth(''); $value = static::$redis->rpop($key_name); $value = json_decode($value, true); return $value; } /* * 删除记录 * @param $dbname 数据库 * @param $key_name key名称 * @return bool 返回值 */ public function delQueue($dbname, $key_name) { static::$redis->select($dbname); static::$redis->auth(''); $res = static::$redis->del($key_name); if($res) return true; else return false; } }
test:
require_once('msgQueue.php'); $msgQueue = new msgQueue(); $key_name = 'queue'; $dbname = '1'; $data = ['a','b','c','d','e','f','g','h']; //这里可以是get或post请求过来的数据 //$msgQueue->delQueue($dbname,$key_name); for($i=0;$i<count($data);$i++){ $msgQueue->inQueue($dbname,$key_name,$data[$i]); } $selectQueue = $msgQueue->selectQueue($dbname,$key_name); var_dump($selectQueue); echo '<br>'; var_dump($msgQueue->outQueue($dbname,$key_name)); $selectQueue = $msgQueue->selectQueue($dbname,$key_name); var_dump($selectQueue);