PHP+Redis消息队列

调用方式

$redis = RedisManager::getInstance();
$queue = json_encode(['queue_id'=>$queueId,'question'=>$question],256);
if($redis->LPush('QA_wecom',$queue)) return Result::Success();

单例

<?php
namespace app\admin\common;
use think\helper\Str;
class RedisManager
{
  private static $handler = null;
  private static $_instance = null;
  private function __construct()
  {
    if (!extension_loaded('redis')) {
      throw new \BadFunctionCallException('未开启Redis扩展');      //判断是否有扩展
    }
    $config = app()->config->get('queue.connections.redis');
    $func = $config['persistent'] ? 'pconnect' : 'connect';
    self::$handler = new \Redis;
    self::$handler->$func($config['host'], $config['port'], $config['timeout']);
    if ('' != $config['password']) {
      self::$handler->auth($config['password']);
    }
    if (0 != $config['select']) {
      self::$handler->select($config['select']);
    }
  }
  /**
   * @return RedisPackage|null 对象
   */
  public static function getInstance()
  {
    if (!(self::$_instance instanceof self)) {
      self::$_instance = new self();
    }
    return self::$_instance;
  }
  /**
   * 禁止外部克隆
   */
  public function __clone()
  {
    trigger_error('Clone is not allow!',E_USER_ERROR);
  }
  /**
   * 写入缓存
   * @param string $key 键名
   * @param string $value 键值
   * @param int $exprie 过期时间 0:永不过期
   * @return bool
   */
  public static function set($key, $value, $exprie = 0)
  {
    if ($exprie == 0) {
      $set = self::$handler->set($key, $value);
    } else {
      $set = self::$handler->setex($key, $exprie, $value);
    }
    return $set;
  }
  /**
   * 读取缓存
   * @param string $key 键值
   * @return mixed
   */
  public static function get($key)
  {
    $fun = is_array($key) ? 'Mget' : 'get';
    return self::$handler->{$fun}($key);
  }
  /**
   * 删除key
   * @param $key
   * @return int
   * @author peter
   * @date 2022-04-09 上午10:39
   */
  public static function delKey($key){
    return self::$handler->del($key);
  }
  /**
   * 获取值长度
   * @param string $key
   * @return int
   */
  public static function lLen($key)
  {
    return self::$handler->lLen($key);
  }
  /**
   * 将一个或多个值插入到列表头部
   * @param $key
   * @param $value
   * @return int
   */
  public static function LPush($key, $value)
  {
    return self::$handler->lPush($key, $value);
  }
  /**
   * 移出并获取列表的第一个元素
   * @param string $key
   * @return string
   */
  public static function lPop($key)
  {
    return self::$handler->lPop($key);
  }
  public static function brPop($queue, $timeout = 0){
    return self::$handler->brPop($queue, $timeout);
  }
  public static function lrange($key,$start,$end){
    return self::$handler->lrange($key,$start,$end);
  }
}

posted @ 2023-07-11 09:47  窦戈  阅读(90)  评论(0编辑  收藏  举报