tp5使用predis/predis包

好久不见. 提交于 2020-01-10 10:58:11

【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>

第一下载predis/predis

第二引用包,添加实例类接口 application/common/Redis.php

<?php

namespace app\common;

use Exception;
use Predis\Client;
use Log;

class Redis
{
    use InstanceTrait;

    public static function conn()
    {

        $parameters = [
            'host' => config('redis.host'),
            'port' => config('redis.port'),
        ];

        if (!empty(config('redis.password'))) {
            $parameters['password'] = config('redis.password');
        }

        return new Client($parameters);

    }

    public function fommatDsn($redisDb = 0)
    {
        $dsn = "redis://";
        if (config('redis.user')) {
            $dsn .= config('redis.user');
        } else {
            $dsn .= "root";
        }

        if (config('redis.password')) {
            $dsn .= ":" . config('redis.password') . "@";
        } else {
            $dsn .= "@";
        }

        if (config('redis.host')) {
            $dsn .= config('redis.host');
        } else {
            $dsn .= "127.0.0.1";
        }

        if (config('redis.port')) {
            $dsn .= ":" . config('redis.port');
        } else {
            $dsn .= ":6379";
        }

        if ($redisDb > 0 && $redisDb < 16) {
            $dsn .= "/" . (int)$redisDb;
        }

        return $dsn;
    }

    public function redisGet($key)
    {
        $value = redis()->get($key);
        if (empty($value)) {
            return ["code" => _MSG_NOT_FOUND, "msg" => "未找到数据", "data" => ""];
        }
        return ["code" => _MSG_SYSTEM_SUCCESS, "msg" => "查询成功", "data" => unserialize($value)];
    }

    public function redisSet($key, $value, $ttl = 60 * 60 * 24 * 15)
    {
        if (!redis()->setex($key, $ttl, serialize($value))) {
            \Log::error("" . __FUNCTION__ . ": 存入redis失败 key=" . $key . " value=" . $value, []);
            return ["code" => _MSG_SYSTEM_ERROR, "msg" => "redis插入失败"];
        }
        return ["code" => _MSG_SYSTEM_SUCCESS, "msg" => "redis插入成功"];
    }

    public function redisDel($key)
    {
        redis()->del($key);
    }

    public function redisMdel($keys)
    {
        redis()->del($keys);
    }

    public function redisHSet($name, $key, $value)
    {
        if (!redis()->hset($name, $key, serialize($value))) {
            \Log::error("" . __FUNCTION__ . ": 存入redis失败 key=" . $key . " value=" . $value);
            return ["code" => _MSG_SYSTEM_ERROR, "msg" => "redis插入失败"];
        }
        return ["code" => _MSG_SYSTEM_SUCCESS, "msg" => "redis插入成功"];
    }

    public function redisHMSet($name, $data)
    {
        if (!redis()->hmset($name, $data)) {
            \Log::error("" . __FUNCTION__ . ": 存入redis失败 key=" . $name . " value=" . serialize($data));
            return ["code" => _MSG_SYSTEM_ERROR, "msg" => "redis插入失败"];
        }
//        redis()->expire($name, 60 * 60 * 24 * 15);
        return ["code" => _MSG_SYSTEM_SUCCESS, "msg" => "redis插入成功"];
    }

    public function redisExpire($redisKey, $ttl)
    {
        redis()->expire($redisKey, $ttl);
    }

    public function redisHMSetInit($name, $data)
    {
        $op = redis()->transaction(function ($tx) use ($name, $data) {
            $tx->del($name);
            $tx->hmset($name, $data); // 倒序插入
            $tx->expire($name, 86400 * 15);
        });
        if (!$op) {
            \Log::error("" . __FUNCTION__ . ": 存入redis失败 key=" . $name . " value=" . serialize($data));
            return ["code" => _MSG_SYSTEM_ERROR, "msg" => "redis插入失败"];
        }
        return ["code" => _MSG_SYSTEM_SUCCESS, "msg" => "redis插入成功"];
    }

    public function redisHSetTrue($name, $key)
    {
        if (!redis()->hset($name, $key, 1)) {
            // \Log::warning(__FUNCTION__.": 存入redis失败 ".$name."[".$key."=1] ", []);
            return ["code" => _MSG_SYSTEM_ERROR, "msg" => "redis插入失败"];
        }
//        redis()->expire($name, 86400 * 15);
        return ["code" => _MSG_SYSTEM_SUCCESS, "msg" => "redis插入成功"];
    }

    public function redisHSetFalse($name, $key)
    {
        if (!redis()->hset($name, $key, 0)) {
            // \Log::warning(__FUNCTION__.": 存入redis失败 ".$name."[".$key."=0] ", []);
            return ["code" => _MSG_SYSTEM_ERROR, "msg" => "redis插入失败"];
        }
        return ["code" => _MSG_SYSTEM_SUCCESS, "msg" => "redis插入成功"];
    }

    public function redisHGetAll($name)
    {
        $value = redis()->hgetall($name);
        if (empty($value)) {
            return [];
        }
        return $value;
    }

    public function redisZadd($key, $score, $value)
    {
        redis()->zadd($key, $score, $value);
    }

    public function redisZrem($key, $list)
    {
        redis()->zrem($key, $list);
    }

// array  zrange($key, $start, $stop, array $options = null)
// array  zrevrange($key, $start, $stop, array $options = null)

    public function redisZRevRange($key, $start, $stop, $options = [])
    {
        $value = redis()->zrevrange($key, $start, $stop, $options);
        if (empty($value)) {
            return ["code" => _MSG_NOT_FOUND, "msg" => "未找到数据", "data" => []];
        }
        return ["code" => _MSG_SYSTEM_SUCCESS, "msg" => "查询成功", "data" => $value];
    }

    public function redisZrange($key, $start, $stop, $options = [])
    {
        $value = redis()->zrange($key, $start, $stop, $options);
        if (empty($value)) {
            return ["code" => _MSG_NOT_FOUND, "msg" => "未找到数据", "data" => []];
        }
        return ["code" => _MSG_SYSTEM_SUCCESS, "msg" => "查询成功", "data" => $value];
    }

    public function redisZrank($key, $member)
    {
        return (int)redis()->zrank($key, $member);
    }


    /**
     * @param $key
     * @param $value
     * @description 初始化 redis list
     */
    public function redisSetList($key, $value)
    {
        krsort($value);
        redis()->transaction(function ($tx) use ($key, $value) {
            $tx->del($key);
            $tx->lpush($key, $value); // 倒序插入
        });
    }

    /**
     * @param $key
     * @param $value
     * @description 左推 redis list
     */
    public function redisLpush($key, $value)
    {
        try {
            redis()->transaction(function ($tx) use ($key, $value) {
                $tx->lpush($key, serialize($value));
                $tx->rPop($key);
            });
        } catch (Exception $e) {
            \Log::error("" . __FUNCTION__ . "存入redis失败" . $e->getMessage(), []);
        }
    }

    public function redisLlen($key)
    {
        if (!redis()->exists($key)) {
            return 0;
        }
        return redis()->llen($key);
    }

    public function redisGetList($key)
    {
        try {
            $list = redis()->lrange($key, 0, -1);
            foreach ($list as $key => $value) {
                $list[$key] = unserialize($value);
            }
            return ["code" => _MSG_SYSTEM_SUCCESS, "msg" => "查询成功", "data" => ["list" => $list]];
        } catch (Exception $e) {
            \Log::error("" . __FUNCTION__ . "获取redis list失败" . $e->getMessage(), []);
            return ["code" => _MSG_NOT_FOUND, "msg" => "未找到数据", "data" => []];
        }
    }

    public function redisLrange($key, $start, $stop)
    {
        try {
            $list = redis()->lrange($key, $start, $stop);
            foreach ($list as $key => $value) {
                $list[$key] = unserialize($value);
            }

            return ["code" => _MSG_SYSTEM_SUCCESS, "msg" => "查询成功", "data" => ["list" => $list]];
        } catch (Exception $e) {
            \Log::error("" . __FUNCTION__ . "获取redis list失败" . $e->getMessage(), []);
            return ["code" => _MSG_NOT_FOUND, "msg" => "未找到数据", "data" => []];
        }
    }

    public function redisMget($list)
    {
        $list = redis()->mget($list);
        foreach ($list as $k => $v) {
            $list[$k] = unserialize($v);
        }
        return $list;
    }

    public function redisIncre($key)
    {
        return redis()->incr($key);
    }

    public function redisHincre($name, $key, $increNum = 1)
    {
        return redis()->hincrby($name, $key, $increNum);
    }

    public function redisHMgetNum($key, $list)
    {
        $list = redis()->hmget($key, $list);
        foreach ($list as $k => $v) {
            $list[$k] = (int)$v;
        }
        return $list;
    }

    public function redisHMget($key, $list)
    {
        $list = redis()->hmget($key, $list);
        return $list;
    }

    public function redisSadd($key, $list)
    {
        redis()->sadd($key, $list);
    }

    public function redisSrem($key, $list)
    {
        redis()->srem($key, $list);
    }

    public function redisScount($key)
    {
        redis()->scard($key);
    }

    public function redisZcard($key)
    {
        return redis()->zcard($key);
    }

    public function redisHautoSet($name, $key, $v)
    {
        try {
            if (redis()->hexists($name, $key)) {
                //redis()->hdel($name, $key);
                $status = 2;
            } else {
                redis()->hset($name, $key, $v);
                $status = 1;
            }
            return $status;
        } catch (Exception $e) {
            return 0;
        }
    }

    public function redisHexists($name, $key)
    {
        return redis()->hexists($name, $key);
    }

    public function redisHlen($key)
    {
        return redis()->hlen($key);
    }

    public function redisHgetKeysAsKey($key)
    {
        $list = redis()->hkeys($key);
        $kv = [];
        if (!empty($list)) {
            foreach ($list as $value) {
                $kv[$value] = 1;
            }
        }
        return $kv;
    }

    public function redisHgetKeys($key)
    {
        $list = redis()->hkeys($key);
        return $list;
    }

    public function redisHdel($name, $keys)
    {
        return redis()->hdel($name, $keys);
    }

    public function redisHget($name, $key)
    {
        return redis()->hget($name, $key);
    }

    /*
     * 有序集合自增长
     */
    public function redisZincrby($key, $increment, $member)
    {
        return redis()->zincrby($key, $increment, $member);
    }

    /*
     * 获取有序集合的分数
     */
    public function redisZscore($key, $member)
    {
        $value = redis()->zscore($key, $member);
        return intval($value);
    }
}

第三helper.php添加redis()方法名thinkphp/helper.php

if (!function_exists('redis')) {

    function redis()
    {
        return \app\common\Redis::conn();
    }
}

Buy me a cup of coffee :)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!