thinkphp6中Redis 的基本使用方法詳解
1.安裝redis
ThinkPHP內(nèi)置支持的緩存類型包括file、memcache、wincache、sqlite、redis。ThinkPHP默認(rèn)使用自帶的采用think\Cache類。(PHPstudy自帶redis)如果沒有跟著下面步驟:
下載地址:https://github.com/tporadowski/redis/releases。
a.解壓到你自己命名的磁盤(最好不好C盤)
b.如何檢驗(yàn)是否有安裝,按住win+r,輸入cmd,在輸入進(jìn)入DOC操作系統(tǒng)窗口。在操作窗口切換到安裝redis的目錄下
c.輸入redis-server.exe redis.windows.conf
看到這個(gè)界面就知道redis已經(jīng)安裝成功。這時(shí)候另啟一個(gè) cmd 窗口,原來的不要關(guān)閉,不然就無法訪問服務(wù)端了。
redis介紹
redis-benchmark.exe #基準(zhǔn)測試
redis-check-aof.exe # aof
redischeck-dump.exe # dump
redis-cli.exe # 客戶端
redis-server.exe # 服務(wù)器
redis.windows.conf # 配置文件
//切換到redis目錄下 redis-cli.exe -h 127.0.0.1 -p 6379 //設(shè)置key set key ABC //取出Key get key
2.配置redis
thinkphp 6 配值路徑config/cache.php
<?php // +---------------------------------------------------------------------- // | 緩存設(shè)置 // +---------------------------------------------------------------------- return [ // 默認(rèn)緩存驅(qū)動(dòng) 'default' => env('cache.driver', 'file'), // 緩存連接方式配置 'stores' => [ 'file' => [ // 驅(qū)動(dòng)方式 'type' => 'File', // 緩存保存目錄 'path' => '', // 緩存前綴 'prefix' => '', // 緩存有效期 0表示永久緩存 'expire' => 0, // 緩存標(biāo)簽前綴 'tag_prefix' => 'tag:', // 序列化機(jī)制 例如 ['serialize', 'unserialize'] 'serialize' => [], ], // 配置Reids 'redis' => [ 'type' => 'redis', 'host' => '127.0.0.1', 'port' => '6379', 'password' => '123456', 'select' => '0', // 全局緩存有效期(0為永久有效) 'expire' => 0, // 緩存前綴 'prefix' => '', 'timeout' => 0, ], ], ];
沒有指定緩存類型的話,默認(rèn)讀取的是default緩存配置,可以動(dòng)態(tài)切換,控制器調(diào)用:
use think\facade\Cache; public function test(){ // 使用文件緩存 Cache::set('name','value',3600); Cache::get('name'); // 使用Redis緩存 Cache::store('redis')->set('name','value',3600); Cache::store('redis')->get('name'); // 切換到文件緩存 Cache::store('default')->set('name','value',3600); Cache::store('default')->get('name'); }
3.thinkphp6 中redis類(調(diào)用下面的方法)
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- // | Copyright (c) 2006~2021 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- declare (strict_types = 1); namespace think\cache\driver; use think\cache\Driver; /** * Redis緩存驅(qū)動(dòng),適合單機(jī)部署、有前端代理實(shí)現(xiàn)高可用的場景,性能最好 * 有需要在業(yè)務(wù)層實(shí)現(xiàn)讀寫分離、或者使用RedisCluster的需求,請使用Redisd驅(qū)動(dòng) * * 要求安裝phpredis擴(kuò)展:https://github.com/nicolasff/phpredis * @author 塵緣 <130775@qq.com> */ class Redis extends Driver { /** @var \Predis\Client|\Redis */ protected $handler; /** * 配置參數(shù) * @var array */ protected $options = [ 'host' => '127.0.0.1', 'port' => 6379, 'password' => '', 'select' => 0, 'timeout' => 0, 'expire' => 0, 'persistent' => false, 'prefix' => '', 'tag_prefix' => 'tag:', 'serialize' => [], ]; /** * 架構(gòu)函數(shù) * @access public * @param array $options 緩存參數(shù) */ public function __construct(array $options = []) { if (!empty($options)) { $this->options = array_merge($this->options, $options); } if (extension_loaded('redis')) { $this->handler = new \Redis; if ($this->options['persistent']) { $this->handler->pconnect($this->options['host'], (int) $this->options['port'], (int) $this->options['timeout'], 'persistent_id_' . $this->options['select']); } else { $this->handler->connect($this->options['host'], (int) $this->options['port'], (int) $this->options['timeout']); } if ('' != $this->options['password']) { $this->handler->auth($this->options['password']); } } elseif (class_exists('\Predis\Client')) { $params = []; foreach ($this->options as $key => $val) { if (in_array($key, ['aggregate', 'cluster', 'connections', 'exceptions', 'prefix', 'profile', 'replication', 'parameters'])) { $params[$key] = $val; unset($this->options[$key]); } } if ('' == $this->options['password']) { unset($this->options['password']); } $this->handler = new \Predis\Client($this->options, $params); $this->options['prefix'] = ''; } else { throw new \BadFunctionCallException('not support: redis'); } if (0 != $this->options['select']) { $this->handler->select((int) $this->options['select']); } } /** * 判斷緩存 * @access public * @param string $name 緩存變量名 * @return bool */ public function has($name): bool { return $this->handler->exists($this->getCacheKey($name)) ? true : false; } /** * 讀取緩存 * @access public * @param string $name 緩存變量名 * @param mixed $default 默認(rèn)值 * @return mixed */ public function get($name, $default = null) { $this->readTimes++; $key = $this->getCacheKey($name); $value = $this->handler->get($key); if (false === $value || is_null($value)) { return $default; } return $this->unserialize($value); } /** * 寫入緩存 * @access public * @param string $name 緩存變量名 * @param mixed $value 存儲數(shù)據(jù) * @param integer|\DateTime $expire 有效時(shí)間(秒) * @return bool */ public function set($name, $value, $expire = null): bool { $this->writeTimes++; if (is_null($expire)) { $expire = $this->options['expire']; } $key = $this->getCacheKey($name); $expire = $this->getExpireTime($expire); $value = $this->serialize($value); if ($expire) { $this->handler->setex($key, $expire, $value); } else { $this->handler->set($key, $value); } return true; } /** * 自增緩存(針對數(shù)值緩存) * @access public * @param string $name 緩存變量名 * @param int $step 步長 * @return false|int */ public function inc(string $name, int $step = 1) { $this->writeTimes++; $key = $this->getCacheKey($name); return $this->handler->incrby($key, $step); } /** * 自減緩存(針對數(shù)值緩存) * @access public * @param string $name 緩存變量名 * @param int $step 步長 * @return false|int */ public function dec(string $name, int $step = 1) { $this->writeTimes++; $key = $this->getCacheKey($name); return $this->handler->decrby($key, $step); } /** * 刪除緩存 * @access public * @param string $name 緩存變量名 * @return bool */ public function delete($name): bool { $this->writeTimes++; $key = $this->getCacheKey($name); $result = $this->handler->del($key); return $result > 0; } /** * 清除緩存 * @access public * @return bool */ public function clear(): bool { $this->writeTimes++; $this->handler->flushDB(); return true; } /** * 刪除緩存標(biāo)簽 * @access public * @param array $keys 緩存標(biāo)識列表 * @return void */ public function clearTag(array $keys): void { // 指定標(biāo)簽清除 $this->handler->del($keys); } /** * 追加TagSet數(shù)據(jù) * @access public * @param string $name 緩存標(biāo)識 * @param mixed $value 數(shù)據(jù) * @return void */ public function append(string $name, $value): void { $key = $this->getCacheKey($name); $this->handler->sAdd($key, $value); } /** * 獲取標(biāo)簽包含的緩存標(biāo)識 * @access public * @param string $tag 緩存標(biāo)簽 * @return array */ public function getTagItems(string $tag): array { $name = $this->getTagKey($tag); $key = $this->getCacheKey($name); return $this->handler->sMembers($key); } }
4.Redis 常用命令操作
Redis支持五種數(shù)據(jù)類型:string(字符串),hash(哈希),list(列表),set(集合)及zset(sorted set:有序集合)。
命令 | 語法 | 作用 |
---|---|---|
set | set name 張三 | 設(shè)置鍵值 |
get | get name | 取出key值 |
del | del name1 name2 | 刪除一個(gè)或者多個(gè)鍵值 |
mset | mset k1 k2 k3 v1 v2 v3 | 設(shè)置多個(gè)鍵值 |
rename | rename key newkey | 改鍵名 |
keys | keys * 慎用(大型服務(wù)器,會dwon,消耗進(jìn)程)keys k? | 查找相應(yīng)的key |
incr | incr key | 指定的key增加1,并返回加1之后的值 |
decr | decr key | 指定的key減1,并返回減1之后的值 |
append | append key value | 把value 追加到key的原值后面 |
– | – | – |
hset | hset key field value | 將哈希表 key 中的字段 field 的值設(shè)為 value 。(場景:添加用戶信息) |
hmset | hmset key field1 value1 [field 2 vaue2] | 同時(shí)將多個(gè) field-value (域-值)對設(shè)置到哈希表 key 中。 |
hget | hget key field | 獲取存儲在哈希表中key的指定字段的值 |
hmget | hmget key field1 field2 | 獲取key的選擇字段和值 |
hkeys | hkeys key | 查對應(yīng)的key中所有的field |
hlen | hlen key | 獲取key的長度 |
hdel | hdel key field | 刪除key中的field與值 |
hexists | hexists key field | 查看哈希表 key 中,指定的字段是否存在。 |
– | – | – |
lpush | lpush key value [value2] | 將一個(gè)或多個(gè)值插入到列表頭部 |
rpush | rpush key value [valus2] | 在列表中添加一個(gè)或多個(gè)值 |
lindex | lindex key index | 通過索引獲取列表中的元素 |
llen | llen key | 獲取列表長度 |
lpop | lpop key | 左刪除并返回值 |
rpop | rpop key | 右刪除并返回值 |
– | – | – |
sadd | sadd key member1 [member2] | 向集合添加一個(gè)或多個(gè)成員,集合里面相同的值的個(gè)數(shù)值算一個(gè)(應(yīng)用場景:標(biāo)簽,社交等) |
smembers | smembers key | 返回集合中的所有成員 |
srem | srem key value1 value2 | 用于移除集合中的一個(gè)或多個(gè)成員元素,不存在的成員元素會被忽略。 |
sismember | sismember key value | 判斷value是否存在集合key中,存在返回1,不存在返回0. |
smove | smove key1 key2 value | 將集合key1里面的value值刪除并添加到集合key2中,如果key1里面value的值不存在,命令就不執(zhí)行,返回0。如果key2已經(jīng)存在value的值,那key1的集合直接執(zhí)行刪除value值。 |
sinter | sinter key1 key2 | key1 key2的交集,返回key1 key2的相同value。 |
sdiff | sdiff key1 key2 | key1 key2的差集,舉例:key1集合{1,2,3} key2集合{2,3,4} .key1 減去 key2={1},key2減去key1={4}(相減去相同的) |
– | – | – |
zadd | zadd key score1 value1 score2 value2 | 向有序集合添加一個(gè)或多個(gè)成員,或者更新已存在成員的分?jǐn)?shù)(應(yīng)用場景:排名、社交等) |
zcard | zcard key | 統(tǒng)計(jì)key 的值的個(gè)數(shù) |
zrange | zrange key start stop withscores | zrange key start stop withscores 把集合排序后,按照分?jǐn)?shù)排序打印出來 |
zrevrange | zrevrange key start stop withscores | 把集合降序排列 |
4.redis數(shù)據(jù)備份與恢復(fù)
redis 127.0.0.1:6379> SAVE //該命令將在 redis 安裝目錄中創(chuàng)建dump.rdb文件。 //如果需要恢復(fù)數(shù)據(jù),只需將備份文件 (dump.rdb) 移動(dòng)到 redis 安裝目錄并啟動(dòng)服務(wù)即可。獲取 redis 目錄可以使用 CONFIG 命令 redis 127.0.0.1:6379> CONFIG GET dir
備注:如果是php 記得要打開redis的擴(kuò)展才能使用
- ThinkPHP6使用JWT+中間件實(shí)現(xiàn)Token驗(yàn)證實(shí)例詳解
- Thinkphp6 配置并使用redis圖文詳解
- ThinkPHP6.0前置、后置中間件區(qū)別
- ThinkPHP6.0 重寫URL去掉Index.php的解決方法
- 基于thinkphp6.0的success、error實(shí)現(xiàn)方法
- thinkphp3.2框架集成QRcode生成二維碼的方法分析
- Thinkphp使用Zxing擴(kuò)展庫解析二維碼內(nèi)容圖文講解
- Thinkphp3.2.3整合phpqrcode生成帶logo的二維碼
- ThinkPHP6使用最新版本Endroid/QrCode生成二維碼的方法實(shí)例
相關(guān)文章
PHP+MariaDB數(shù)據(jù)庫操作基本技巧備忘總結(jié)
這篇文章主要介紹了PHP+MariaDB數(shù)據(jù)庫操作基本技巧,結(jié)合實(shí)例形式總結(jié)分析了PHP+MariaDB數(shù)據(jù)庫連接、判斷以及基于PHP+MariaDB的用戶登陸、管理、刪除等相關(guān)操作實(shí)現(xiàn)技巧與注意事項(xiàng),需要的朋友可以參考下2018-05-05PHP 中關(guān)于ord($str)>0x80的詳細(xì)說明
為了識別雙字節(jié)的字符,比如漢字或日文韓文等都是占兩字節(jié)的,每字節(jié)高位為1,而一般西文字符只有一個(gè)字節(jié),七位有效編碼,高位為0而0x80對應(yīng)的二進(jìn)制代碼為1000 0000,最高位為一,代表漢字.漢字編碼格式通稱為10格式. 一個(gè)漢字占2字節(jié),但只代表一個(gè)字符2012-09-09php操作Redis數(shù)據(jù)庫基本示例【安裝、連接、設(shè)置、查詢、斷開】
這篇文章主要介紹了php操作Redis數(shù)據(jù)庫的方法,較為詳細(xì)的分析了redis擴(kuò)展的安裝、php連接redis、設(shè)置、查詢及斷開redis相關(guān)實(shí)現(xiàn)技巧與操作注意事項(xiàng),需要的朋友可以參考下2023-07-07