翼度科技»论坛 编程开发 PHP 查看内容

thinkphp6中Redis 的基本使用方法详解

4

主题

4

帖子

12

积分

新手上路

Rank: 1

积分
12
1.安装redis

ThinkPHP内置支持的缓存类型包括file、memcache、wincache、sqlite、redis。ThinkPHP默认使用自带的采用think\Cache类。(PHPstudy自带redis)如果没有跟着下面步骤:
下载地址:https://github.com/tporadowski/redis/releases。
a.解压到你自己命名的磁盘(最好不好C盘)
b.如何检验是否有安装,按住win+r,输入cmd,在输入进入DOC操作系统窗口。在操作窗口切换到安装redis的目录下

c.输入redis-server.exe redis.windows.conf

看到这个界面就知道redis已经安装成功。这时候另启一个 cmd 窗口,原来的不要关闭,不然就无法访问服务端了。
redis介绍
redis-benchmark.exe #基准测试
redis-check-aof.exe # aof
redischeck-dump.exe # dump
redis-cli.exe # 客户端
redis-server.exe # 服务器
redis.windows.conf # 配置文件
  1. //切换到redis目录下
  2. redis-cli.exe -h 127.0.0.1 -p 6379
  3. //设置key
  4. set key ABC
  5. //取出Key
  6. get key
复制代码

2.配置redis

thinkphp 6 配值路径config/cache.php
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | 缓存设置
  4. // +----------------------------------------------------------------------
  5. return [
  6.     // 默认缓存驱动
  7.     'default' => env('cache.driver', 'file'),
  8.     // 缓存连接方式配置
  9.     'stores'  => [
  10.         'file' => [
  11.             // 驱动方式
  12.             'type'       => 'File',
  13.             // 缓存保存目录
  14.             'path'       => '',
  15.             // 缓存前缀
  16.             'prefix'     => '',
  17.             // 缓存有效期 0表示永久缓存
  18.             'expire'     => 0,
  19.             // 缓存标签前缀
  20.             'tag_prefix' => 'tag:',
  21.             // 序列化机制 例如 ['serialize', 'unserialize']
  22.             'serialize'  => [],
  23.         ],
  24.         // 配置Reids
  25.         'redis'    =>    [
  26.             'type'     => 'redis',
  27.             'host'     => '127.0.0.1',
  28.             'port'     => '6379',
  29.             'password' => '123456',
  30.             'select'   => '0',
  31.             // 全局缓存有效期(0为永久有效)
  32.             'expire'   => 0,
  33.             // 缓存前缀
  34.             'prefix'   => '',
  35.             'timeout'  => 0,
  36.         ],
  37.     ],
  38. ];
复制代码
没有指定缓存类型的话,默认读取的是default缓存配置,可以动态切换,控制器调用:
  1. use think\facade\Cache;
  2. public function test(){
  3.                 // 使用文件缓存
  4.                 Cache::set('name','value',3600);
  5.                 Cache::get('name');
  6.                 // 使用Redis缓存
  7.                 Cache::store('redis')->set('name','value',3600);
  8.                 Cache::store('redis')->get('name');
  9.                 // 切换到文件缓存
  10.                 Cache::store('default')->set('name','value',3600);
  11.                 Cache::store('default')->get('name');
  12.     }
复制代码
3.thinkphp6 中redis类(调用下面的方法)
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006~2021 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: liu21st <liu21st@gmail.com>
  10. // +----------------------------------------------------------------------
  11. declare (strict_types = 1);
  12. namespace think\cache\driver;
  13. use think\cache\Driver;
  14. /**
  15. * Redis缓存驱动,适合单机部署、有前端代理实现高可用的场景,性能最好
  16. * 有需要在业务层实现读写分离、或者使用RedisCluster的需求,请使用Redisd驱动
  17. *
  18. * 要求安装phpredis扩展:https://github.com/nicolasff/phpredis
  19. * @author    尘缘 <130775@qq.com>
  20. */
  21. class Redis extends Driver
  22. {
  23.     /** @var \Predis\Client|\Redis */
  24.     protected $handler;
  25.     /**
  26.      * 配置参数
  27.      * @var array
  28.      */
  29.     protected $options = [
  30.         'host'       => '127.0.0.1',
  31.         'port'       => 6379,
  32.         'password'   => '',
  33.         'select'     => 0,
  34.         'timeout'    => 0,
  35.         'expire'     => 0,
  36.         'persistent' => false,
  37.         'prefix'     => '',
  38.         'tag_prefix' => 'tag:',
  39.         'serialize'  => [],
  40.     ];
  41.     /**
  42.      * 架构函数
  43.      * @access public
  44.      * @param array $options 缓存参数
  45.      */
  46.     public function __construct(array $options = [])
  47.     {
  48.         if (!empty($options)) {
  49.             $this->options = array_merge($this->options, $options);
  50.         }
  51.         if (extension_loaded('redis')) {
  52.             $this->handler = new \Redis;
  53.             if ($this->options['persistent']) {
  54.                 $this->handler->pconnect($this->options['host'], (int) $this->options['port'], (int) $this->options['timeout'], 'persistent_id_' . $this->options['select']);
  55.             } else {
  56.                 $this->handler->connect($this->options['host'], (int) $this->options['port'], (int) $this->options['timeout']);
  57.             }
  58.             if ('' != $this->options['password']) {
  59.                 $this->handler->auth($this->options['password']);
  60.             }
  61.         } elseif (class_exists('\Predis\Client')) {
  62.             $params = [];
  63.             foreach ($this->options as $key => $val) {
  64.                 if (in_array($key, ['aggregate', 'cluster', 'connections', 'exceptions', 'prefix', 'profile', 'replication', 'parameters'])) {
  65.                     $params[$key] = $val;
  66.                     unset($this->options[$key]);
  67.                 }
  68.             }
  69.             if ('' == $this->options['password']) {
  70.                 unset($this->options['password']);
  71.             }
  72.             $this->handler = new \Predis\Client($this->options, $params);
  73.             $this->options['prefix'] = '';
  74.         } else {
  75.             throw new \BadFunctionCallException('not support: redis');
  76.         }
  77.         if (0 != $this->options['select']) {
  78.             $this->handler->select((int) $this->options['select']);
  79.         }
  80.     }
  81.     /**
  82.      * 判断缓存
  83.      * @access public
  84.      * @param string $name 缓存变量名
  85.      * @return bool
  86.      */
  87.     public function has($name): bool
  88.     {
  89.         return $this->handler->exists($this->getCacheKey($name)) ? true : false;
  90.     }
  91.     /**
  92.      * 读取缓存
  93.      * @access public
  94.      * @param string $name    缓存变量名
  95.      * @param mixed  $default 默认值
  96.      * @return mixed
  97.      */
  98.     public function get($name, $default = null)
  99.     {
  100.         $this->readTimes++;
  101.         $key   = $this->getCacheKey($name);
  102.         $value = $this->handler->get($key);
  103.         if (false === $value || is_null($value)) {
  104.             return $default;
  105.         }
  106.         return $this->unserialize($value);
  107.     }
  108.     /**
  109.      * 写入缓存
  110.      * @access public
  111.      * @param string            $name   缓存变量名
  112.      * @param mixed             $value  存储数据
  113.      * @param integer|\DateTime $expire 有效时间(秒)
  114.      * @return bool
  115.      */
  116.     public function set($name, $value, $expire = null): bool
  117.     {
  118.         $this->writeTimes++;
  119.         if (is_null($expire)) {
  120.             $expire = $this->options['expire'];
  121.         }
  122.         $key    = $this->getCacheKey($name);
  123.         $expire = $this->getExpireTime($expire);
  124.         $value  = $this->serialize($value);
  125.         if ($expire) {
  126.             $this->handler->setex($key, $expire, $value);
  127.         } else {
  128.             $this->handler->set($key, $value);
  129.         }
  130.         return true;
  131.     }
  132.     /**
  133.      * 自增缓存(针对数值缓存)
  134.      * @access public
  135.      * @param string $name 缓存变量名
  136.      * @param int    $step 步长
  137.      * @return false|int
  138.      */
  139.     public function inc(string $name, int $step = 1)
  140.     {
  141.         $this->writeTimes++;
  142.         $key = $this->getCacheKey($name);
  143.         return $this->handler->incrby($key, $step);
  144.     }
  145.     /**
  146.      * 自减缓存(针对数值缓存)
  147.      * @access public
  148.      * @param string $name 缓存变量名
  149.      * @param int    $step 步长
  150.      * @return false|int
  151.      */
  152.     public function dec(string $name, int $step = 1)
  153.     {
  154.         $this->writeTimes++;
  155.         $key = $this->getCacheKey($name);
  156.         return $this->handler->decrby($key, $step);
  157.     }
  158.     /**
  159.      * 删除缓存
  160.      * @access public
  161.      * @param string $name 缓存变量名
  162.      * @return bool
  163.      */
  164.     public function delete($name): bool
  165.     {
  166.         $this->writeTimes++;
  167.         $key    = $this->getCacheKey($name);
  168.         $result = $this->handler->del($key);
  169.         return $result > 0;
  170.     }
  171.     /**
  172.      * 清除缓存
  173.      * @access public
  174.      * @return bool
  175.      */
  176.     public function clear(): bool
  177.     {
  178.         $this->writeTimes++;
  179.         $this->handler->flushDB();
  180.         return true;
  181.     }
  182.     /**
  183.      * 删除缓存标签
  184.      * @access public
  185.      * @param array $keys 缓存标识列表
  186.      * @return void
  187.      */
  188.     public function clearTag(array $keys): void
  189.     {
  190.         // 指定标签清除
  191.         $this->handler->del($keys);
  192.     }
  193.     /**
  194.      * 追加TagSet数据
  195.      * @access public
  196.      * @param string $name  缓存标识
  197.      * @param mixed  $value 数据
  198.      * @return void
  199.      */
  200.     public function append(string $name, $value): void
  201.     {
  202.         $key = $this->getCacheKey($name);
  203.         $this->handler->sAdd($key, $value);
  204.     }
  205.     /**
  206.      * 获取标签包含的缓存标识
  207.      * @access public
  208.      * @param string $tag 缓存标签
  209.      * @return array
  210.      */
  211.     public function getTagItems(string $tag): array
  212.     {
  213.         $name = $this->getTagKey($tag);
  214.         $key  = $this->getCacheKey($name);
  215.         return $this->handler->sMembers($key);
  216.     }
  217. }
复制代码
4.Redis 常用命令操作

Redis支持五种数据类型:string(字符串),hash(哈希),list(列表),set(集合)及zset(sorted set:有序集合)。
命令语法作用setset name 张三设置键值getget name取出key值deldel name1 name2删除一个或者多个键值msetmset k1 k2 k3 v1 v2 v3设置多个键值renamerename key newkey改键名keyskeys * 慎用(大型服务器,会dwon,消耗进程)keys k?查找相应的keyincrincr key指定的key增加1,并返回加1之后的值decrdecr key指定的key减1,并返回减1之后的值appendappend key value把value 追加到key的原值后面–––hsethset key field value将哈希表 key 中的字段 field 的值设为 value 。(场景:添加用户信息)hmsethmset key field1 value1 [field 2 vaue2]同时将多个 field-value (域-值)对设置到哈希表 key 中。hgethget key field获取存储在哈希表中key的指定字段的值hmgethmget key field1 field2获取key的选择字段和值hkeyshkeys key查对应的key中所有的fieldhlenhlen key获取key的长度hdelhdel key field删除key中的field与值hexistshexists key field查看哈希表 key 中,指定的字段是否存在。–––lpushlpush key value [value2]将一个或多个值插入到列表头部rpushrpush key value [valus2]在列表中添加一个或多个值lindexlindex key index通过索引获取列表中的元素llenllen key获取列表长度lpoplpop key左删除并返回值rpoprpop key右删除并返回值–––saddsadd key member1 [member2]向集合添加一个或多个成员,集合里面相同的值的个数值算一个(应用场景:标签,社交等)smemberssmembers key返回集合中的所有成员sremsrem key value1 value2用于移除集合中的一个或多个成员元素,不存在的成员元素会被忽略。sismembersismember key value判断value是否存在集合key中,存在返回1,不存在返回0.smovesmove key1 key2 value将集合key1里面的value值删除并添加到集合key2中,如果key1里面value的值不存在,命令就不执行,返回0。如果key2已经存在value的值,那key1的集合直接执行删除value值。sintersinter key1 key2key1 key2的交集,返回key1 key2的相同value。sdiffsdiff key1 key2key1 key2的差集,举例:key1集合{1,2,3} key2集合{2,3,4} .key1 减去 key2={1},key2减去key1={4}(相减去相同的)–––zaddzadd key score1 value1 score2 value2向有序集合添加一个或多个成员,或者更新已存在成员的分数(应用场景:排名、社交等)zcardzcard key统计key 的值的个数zrangezrange key start stop withscoreszrange key start stop withscores 把集合排序后,按照分数排序打印出来zrevrangezrevrange key start stop withscores把集合降序排列4.redis数据备份与恢复
  1. redis 127.0.0.1:6379> SAVE
  2. //该命令将在 redis 安装目录中创建dump.rdb文件。
  3. //如果需要恢复数据,只需将备份文件 (dump.rdb) 移动到 redis 安装目录并启动服务即可。获取 redis 目录可以使用 CONFIG 命令
  4. redis 127.0.0.1:6379> CONFIG GET dir
复制代码
备注:如果是php 记得要打开redis的扩展才能使用

来源:https://www.jb51.net/program/2906238x9.htm
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x

举报 回复 使用道具