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 窗口,原來(lái)的不要關(guān)閉,不然就無(wú)法訪問服務(wù)端了。
redis介紹
redis-benchmark.exe #基準(zhǔn)測(cè)試
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)高可用的場(chǎng)景,性能最好
* 有需要在業(yè)務(wù)層實(shí)現(xiàn)讀寫分離、或者使用RedisCluster的需求,請(qǐng)使用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 存儲(chǔ)數(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;
}
/**
* 自增緩存(針對(duì)數(shù)值緩存)
* @access public
* @param string $name 緩存變量名
* @param int $step 步長(zhǎng)
* @return false|int
*/
public function inc(string $name, int $step = 1)
{
$this->writeTimes++;
$key = $this->getCacheKey($name);
return $this->handler->incrby($key, $step);
}
/**
* 自減緩存(針對(duì)數(shù)值緩存)
* @access public
* @param string $name 緩存變量名
* @param int $step 步長(zhǎng)
* @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)識(shí)列表
* @return void
*/
public function clearTag(array $keys): void
{
// 指定標(biāo)簽清除
$this->handler->del($keys);
}
/**
* 追加TagSet數(shù)據(jù)
* @access public
* @param string $name 緩存標(biāo)識(shí)
* @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)識(shí)
* @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:有序集合)。
| 命令 | 語(yǔ)法 | 作用 |
|---|---|---|
| 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ù)器,會(huì)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 。(場(chǎng)景:添加用戶信息) |
| hmset | hmset key field1 value1 [field 2 vaue2] | 同時(shí)將多個(gè) field-value (域-值)對(duì)設(shè)置到哈希表 key 中。 |
| hget | hget key field | 獲取存儲(chǔ)在哈希表中key的指定字段的值 |
| hmget | hmget key field1 field2 | 獲取key的選擇字段和值 |
| hkeys | hkeys key | 查對(duì)應(yīng)的key中所有的field |
| hlen | hlen key | 獲取key的長(zhǎng)度 |
| 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 | 通過(guò)索引獲取列表中的元素 |
| llen | llen key | 獲取列表長(zhǎng)度 |
| lpop | lpop key | 左刪除并返回值 |
| rpop | rpop key | 右刪除并返回值 |
| – | – | – |
| sadd | sadd key member1 [member2] | 向集合添加一個(gè)或多個(gè)成員,集合里面相同的值的個(gè)數(shù)值算一個(gè)(應(yīng)用場(chǎng)景:標(biāo)簽,社交等) |
| smembers | smembers key | 返回集合中的所有成員 |
| srem | srem key value1 value2 | 用于移除集合中的一個(gè)或多個(gè)成員元素,不存在的成員元素會(huì)被忽略。 |
| 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)用場(chǎng)景:排名、社交等) |
| zcard | zcard key | 統(tǒng)計(jì)key 的值的個(gè)數(shù) |
| zrange | zrange key start stop withscores | zrange key start stop withscores 把集合排序后,按照分?jǐn)?shù)排序打印出來(lái) |
| 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ò)展庫(kù)解析二維碼內(nèi)容圖文講解
- Thinkphp3.2.3整合phpqrcode生成帶logo的二維碼
- ThinkPHP6使用最新版本Endroid/QrCode生成二維碼的方法實(shí)例
相關(guān)文章
php查看一個(gè)變量的占用內(nèi)存的實(shí)例代碼
在本篇文章里小編給各位分享的是關(guān)于php查看一個(gè)變量的占用內(nèi)存的實(shí)例代碼,需要的朋友們可以學(xué)習(xí)下。2020-03-03
PHP多線程抓取網(wǎng)頁(yè)實(shí)現(xiàn)代碼
PHP 利用 Curl Functions 可以完成各種傳送文件操作,比如模擬瀏覽器發(fā)送GET,POST請(qǐng)求等等。2010-07-07
詳解php中implode explode serialize json msgpack性能對(duì)比
這篇文章主要介紹了php中implode/explode、serialize、json、 msgpack性能對(duì)比,對(duì)性能感興趣的同學(xué),可以參考下2021-04-04
php array_walk() 數(shù)組函數(shù)
函數(shù)array_walk():單一數(shù)組回調(diào)函數(shù)---對(duì)數(shù)組中的每個(gè)成員應(yīng)用用戶函數(shù)2011-07-07
php調(diào)用Google translate_tts api實(shí)現(xiàn)代碼
以下是對(duì)php調(diào)用Google translate_tts api的實(shí)現(xiàn)代碼進(jìn)行了分析介紹,需要的朋友可以過(guò)來(lái)參考下2013-08-08
簡(jiǎn)單實(shí)現(xiàn)限定phpmyadmin訪問ip的方法
如果你需要限定phpmyadmin特定的ip地址段進(jìn)行訪問,一個(gè)簡(jiǎn)單的方式可以在配置文件中進(jìn)行簡(jiǎn)單限定。2013-03-03
PHP中isset與array_key_exists的區(qū)別實(shí)例分析
這篇文章主要介紹了PHP中isset與array_key_exists的區(qū)別,較為詳細(xì)的分析了isset與array_key_exists使用中的區(qū)別,并實(shí)例分析其具體用法,需要的朋友可以參考下2015-06-06
php中動(dòng)態(tài)調(diào)用函數(shù)的方法
這篇文章主要介紹了php中動(dòng)態(tài)調(diào)用函數(shù)的方法,實(shí)例分析了php動(dòng)態(tài)函數(shù)的實(shí)現(xiàn)原理與具體實(shí)現(xiàn)步驟,需要的朋友可以參考下2015-03-03
PHP下對(duì)數(shù)組進(jìn)行排序的函數(shù)
如果你已經(jīng)使用了一段時(shí)間PHP的話,那么,你應(yīng)該已經(jīng)對(duì)它的數(shù)組比較熟悉了——這種數(shù)據(jù)結(jié)構(gòu)允許你在單個(gè)變量中存儲(chǔ)多個(gè)值,并且可以把它們作為一個(gè)集合進(jìn)行操作。2010-08-08
PHP數(shù)據(jù)庫(kù)操作之基于Mysqli的數(shù)據(jù)庫(kù)操作類庫(kù)
Mysqli 是什么,我這里也不進(jìn)行描述了。因?yàn)榫W(wǎng)上關(guān)于 Mysqli 的教程數(shù)不勝數(shù),我這里為大家介紹一款基于 Mysqli 的操作數(shù)據(jù)庫(kù)類(M.class.php)2014-04-04

