PHP封装一个redis类。

<?php

namespace App\Services;

use App\Handlers\RedisKeyHandler;

/**
* Redis操作类
* 2020-7-4 16:39:09
* Class RedisServices
* @package App\Services
*/
class RedisServices
{

private static $_instance = '';
private $redis;

private function __construct()
{

if (!extension_loaded('redis')) {
exit('请在服务器安装 redis扩展');
}

$this->redis = new \Redis();
$this->redis->connect(env('REDIS_HOST', '127.0.0.1'), env('REDIS_PORT', 6379));
$this->redis->auth(env('REDIS_PASSWORD', ''));
$this->redis->select(14); // 选择默认14库
}

private function __clone()
{
}

public static function getInstance()
{
if (!self::$_instance instanceof RedisServices) {
self::$_instance = new RedisServices();
}
return self::$_instance;
}

/**
* 获取 设置 set, setnx, get, del, exists, setex, psetex, hset, hget, hgetall, lpush, lpop, rpush, rpop, llen, hlen, lindex, sadd, smembers, spop, zadd, , ,
* @param $name
* @param $arguments
* @return string
*/
public function __call($name, $arguments)
{
if (empty($name)) return false;
if (empty($arguments)) return false;

$count = count($arguments);
$result = '';
switch ($count) {
case 1:
$result = $this->redis->$name($arguments['0']);
break;
case 2:
$result = $this->redis->$name($arguments['0'], $arguments['1']);
break;
case 3:
$result = $this->redis->$name($arguments['0'], $arguments['1'], $arguments['2']);
break;
default:
break;
}
return $result;
}


/**
* 维护fd=uid的有序集合
* @param string $model
* @param int $fd
* @param int $uid
* @param bool $isDel 清理fd 此时必须传fd
* @return bool|string|void
* @throws \EasySwoole\Redis\Exception\RedisException
*/
static function fdList($fd = 0, $uid = 0, $isDel = false)
{

$key = RedisKeyHandler::WEB_SOCKET_FD_USER;

if ($isDel && $fd) {
return self::getInstance()->zRemRangeByScore($key, $fd, $fd);
}
if ($fd && $uid) {
return self::getInstance()->zAdd($key, $fd, $uid);
}

if ($fd) {
return self::getInstance()->zRangeByScore($key, $fd, $fd, ['withScores' => false, 'limit' => array(0, 1)]);
}

if ($uid) {
return self::getInstance()->zScore($key, $uid);
}
}


}

posted on 2020-07-18 14:34  githup  阅读(531)  评论(0)    收藏  举报

导航