tp5中简单封装redis类

本文介绍了如何在ThinkPHP5框架下封装Redis客户端类RedisClient和Redis缓存管理类RedisCache。RedisClient负责连接和管理Redis实例,而RedisCache提供了获取、设置和删除缓存的方法,方便在应用中使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第一步:

在common目录新建redis目录,在common\redis新建文件RedisClient.php

内容如下:

namespace app\common\redis;

/**
 * Redis 客户端封装
 *
 * @category Common
 * @package  Common
 * @author   kxl
 */
class RedisClient
{
    //实例字典, 以实例名称为KEY, 对象实例为值
    protected static $dict = array();
    //配置信息
//    private  $redis = array(
//        'host'=>'172.21.20.13',
//        'port'=>'6379',
//        'timeout'=>'0',
//        'retry'=>'0',
//        'readTimeout'=>'0',
//        'auth'=>'ZJ1X8fZRuQndScDF7rTW'
//    );


    private  $redis = array(
        'host'=>'',
        'port'=>'',
        'timeout'=>'0',
        'retry'=>'0',
        'readTimeout'=>'0',
        'auth'=>''
    );


    public function __construct()
    {
        $this->host    =getenv('REDIS_HOST');  //主机域名
        $this->port    =!empty(getenv('REDIS_PORT'))?getenv('REDIS_PORT'):6379;  //端口
        $this->timeout =$this->redis['timeout'];      //连接超时时间,以秒为单位, 默认0为无限
        $this->retry   =$this->redis['retry'];       //连接重试间隔时间, 以毫秒为单位
        $this->readTimeout    =$this->redis['readTimeout'];     //读超时时间,以秒为单位, 默认0无限
        $this->auth    =getenv('REDIS_PASSWORD');      //检测给定的密码和配置文件中的密码是否相符,//设置密码
    }

    /**
     * 获取数据库单实例
     * @param [ $name      ] 实例名
     * @param [ $className ] 类名
     * @param [ $data      ] 构造函数参数
     * @return object 单例对象实例
     */
    public static function getInstance($name, $data = array())
    {
        if (!$name) {
            return null;
        }

        if (!isset(self::$dict[$name])) {
            if ($data) {
                self::$dict[$name]= new \Redis($data);
            } else {
                self::$dict[$name]= new \Redis();
            }
        }
        return self::$dict[$name];
    }


    /**
     * 取得redis client
     *
     * @param [ $name ] 实例名字
     *
     * @return object redis
     */
    public  function getClient($name = 'redis')
    {
        $redis = self::getInstance($name);
        if (!isset($this->host)) {
            return false;
        }
        $host = $this->host;
        //连接端口,默认为6379
        $port = 6379;
        if (isset($this->port)) {
            $port = intval($this->port);
        }

        //连接超时时间,以秒为单位, 默认0为无限
        $timeout = 0;
        if (isset($this->timeout)) {
            $timeout = intval($this->timeout);
        }

        //连接重试间隔时间, 以毫秒为单位
        $retry = 0;
        if (isset($this->retry)) {
            $retry = intval($this->retry);
        }

        //读超时时间,以秒为单位, 默认0无限
        $readTimeout = 0;
        if (isset($this->readTimeout)) {
            $readTimeout = floatval($this->readTimeout);
        }
        if (!$redis->connect($host, $port, $timeout, null, $retry)) {
            return  false;
        }
        if (isset($this->auth)) {
            $auth = trim($this->auth);
            if (!$redis->auth($auth)) {
                return false;
            }
        }
        return $redis;
    }
}

 

第二步:在common\redis新建文件RedisCache.php文件

namespace app\common\redis;
use app\common\redis\RedisClient;

/**
 * Redis缓存管理
 */
class RedisCache
{
    protected static $prefix = 'xiaodong_';
    /**
     * 获取缓存数据
     *
     * @param [ $name ] 缓存key名字
     *
     * @return string 缓存数据
     */
    public static function get($name)
    {
        $RedisClient = new RedisClient();
        $redis = $RedisClient->getClient();
        if (!$redis) {
            return false;
        }

        $data = $redis->get(self::$prefix.$name);
        if (!$data) {
            return false;
        }

        if ($data[0] =='[' || $data[0]=='{') {
            $data = json_decode($data, true);
        }
        return $data;
    }

    /**
     * 设置缓存数据
     *
     * @param [ $name   ] 缓存key名字
     * @param [ $data   ] 缓存数据
     * @param [ $expire ] 过期时间 0为不过期
     *
     * @return string 缓存数据
     */
    public static function set($name, $data, $expire = 0)
    {
        $RedisClient = new RedisClient();
        $redis = $RedisClient->getClient();
        if (!$redis) {
            return false;
        }
        if (is_array($data) || is_object($data)) {
            //数组和对象转换为JSON
            $data = json_encode(
                $data,
                JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES
            );
        }

        if ($expire<=0) {
            return  $redis->set(self::$prefix.$name, $data);
        }
        return  $redis->setEx(self::$prefix.$name, $expire, $data);
    }

    /**
     * 删除缓存数据
     *
     * @param [ $name ] 缓存key名字
     *
     * @return Mixed
     */
    public static function del($name)
    {
        $RedisClient = new RedisClient();
        $redis = $RedisClient->getClient();
        if (!$redis) {
            return false;
        }
        return  $redis->del(self::$prefix.$name);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值