Redis.php

本文涉及的产品
云数据库 Tair(兼容Redis),内存型 2GB
Redis 开源版,标准版 2GB
推荐场景:
搭建游戏排行榜
简介: Redis.php
<?php
/**
 * Created by PhpStorm.
 * User: 郑好
 * Date: 2019/3/6
 * Time: 上午10:23
 */
namespace app\common;
use Exception;
use Predis\Client;
use Log;
use think\console\command\Lists;
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 redisGetV2($key)
    {
        return redis()->get($key);
    }
    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插入成功"];
    }
    //命令用于设置 key 的过期时间,key 过期后将不再可用。单位以秒计。
    public function redisExpire($redisKey, $ttl)
    {
        redis()->expire($redisKey, $ttl);
    }
    //命令用于设置 key 的过期时间,key 过期后将不再可用。单位以毫计。
    public function redisPExpire($redisKey, $ttl)
    {
        redis()->pexpire($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 ["code" => _MSG_SYSTEM_ERROR, "msg" => "获取失败", "data" => []];
        }
        return ["code" => _MSG_SYSTEM_SUCCESS, "msg" => "获取成功", "data" => $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 redisZrangeByscore($key, $max, $min, $options = [])
    {
        $value = redis()->zrevrangebyscore($key, $max, $min, $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);
    }
    /*
     * 如果不存在设置键值,如果存在返回0
     */
    public function redisSetNx($key, $value)
    {
        return redis()->setnx($key, $value);
    }
    /*
     * redis 锁
     */
    public function redisSetNxTime($key, $value, $time)
    {
        return redis()->set($key, $value, 'ex', $time, 'nx');
    }
    /*
     * redis 队列右进
     */
    public function redisRPush($key, $value)
    {
        return redis()->rpush($key, $value);
    }
    /*
     * redis 队列左出
     */
    public function redisLPop($key)
    {
        return redis()->lpop($key);
    }
    /*
     * 判断一个是否是否在一个无序集合内
     * return bool
     */
    public function redisSismember($key, $value)
    {
        $res = redis()->sismember($key, $value);
        if ($res) {
            return true;
        } else {
            return false;
        }
    }
    /**
     * 返回有序集合分数内的总数
     */
    public function redisZcount($key, $min, $max)
    {
        return redis()->zcount($key, $min, $max);
    }
    /**
     * 列出符合条件的key
     * @param $pattern
     * @return array
     */
    public function redisKeys($pattern)
    {
        return redis()->keys($pattern);
    }
}



相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore &nbsp; &nbsp; ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库&nbsp;ECS 实例和一台目标数据库&nbsp;RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&amp;RDS资源,30分钟完成数据库上云实战!https://developer.aliyun.com/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
目录
相关文章
|
7月前
|
NoSQL PHP Redis
PHP Redis 封装
PHP Redis 封装
42 0
|
1月前
|
存储 NoSQL 关系型数据库
PHP 使用 Redis
10月更文挑战第22天
35 6
|
7月前
|
NoSQL PHP Redis
PHP 操作Redis
PHP 操作Redis
56 0
|
NoSQL PHP Redis
php72 安装redis
php72w-pecl-redis
185 0
|
NoSQL Linux PHP
php7安装redis6扩展
php7安装redis6扩展
185 0
|
存储 NoSQL Java
**PHP 使用 Redis
http://www.w3cschool.cc/redis/redis-php.html 安装 开始在 PHP 中使用 Redis 前, 我们需要确保已经安装了 redis 服务及 PHP redis 驱动,且你的机器上能正常使用 PHP。
1131 1