欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時(shí)間:2023年06月29日 09:11:05   作者:@碼猿  
這篇文章主要介紹了thinkphp6中Redis 的基本使用方法,結(jié)合實(shí)例形式詳細(xì)講述了redis的安裝、配置、以及thinkphp6操作redis的基本實(shí)現(xiàn)技巧與相關(guān)注意事項(xiàng),需要的朋友可以參考下

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:有序集合)。

命令語法作用
setset name 張三設(shè)置鍵值
getget name取出key值
deldel name1 name2刪除一個(gè)或者多個(gè)鍵值
msetmset k1 k2 k3 v1 v2 v3設(shè)置多個(gè)鍵值
renamerename key newkey改鍵名
keyskeys * 慎用(大型服務(wù)器,會dwon,消耗進(jìn)程)keys k?查找相應(yīng)的key
incrincr key指定的key增加1,并返回加1之后的值
decrdecr key指定的key減1,并返回減1之后的值
appendappend key value把value 追加到key的原值后面
hsethset key field value將哈希表 key 中的字段 field 的值設(shè)為 value 。(場景:添加用戶信息)
hmsethmset key field1 value1 [field 2 vaue2]同時(shí)將多個(gè) field-value (域-值)對設(shè)置到哈希表 key 中。
hgethget key field獲取存儲在哈希表中key的指定字段的值
hmgethmget key field1 field2獲取key的選擇字段和值
hkeyshkeys key查對應(yīng)的key中所有的field
hlenhlen key獲取key的長度
hdelhdel key field刪除key中的field與值
hexistshexists key field查看哈希表 key 中,指定的字段是否存在。
lpushlpush key value [value2]將一個(gè)或多個(gè)值插入到列表頭部
rpushrpush key value [valus2]在列表中添加一個(gè)或多個(gè)值
lindexlindex key index通過索引獲取列表中的元素
llenllen key獲取列表長度
lpoplpop key左刪除并返回值
rpoprpop key右刪除并返回值
saddsadd key member1 [member2]向集合添加一個(gè)或多個(gè)成員,集合里面相同的值的個(gè)數(shù)值算一個(gè)(應(yīng)用場景:標(biāo)簽,社交等)
smemberssmembers key返回集合中的所有成員
sremsrem key value1 value2用于移除集合中的一個(gè)或多個(gè)成員元素,不存在的成員元素會被忽略。
sismembersismember key value判斷value是否存在集合key中,存在返回1,不存在返回0.
smovesmove key1 key2 value將集合key1里面的value值刪除并添加到集合key2中,如果key1里面value的值不存在,命令就不執(zhí)行,返回0。如果key2已經(jīng)存在value的值,那key1的集合直接執(zhí)行刪除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向有序集合添加一個(gè)或多個(gè)成員,或者更新已存在成員的分?jǐn)?shù)(應(yīng)用場景:排名、社交等)
zcardzcard key統(tǒng)計(jì)key 的值的個(gè)數(shù)
zrangezrange key start stop withscoreszrange key start stop withscores 把集合排序后,按照分?jǐn)?shù)排序打印出來
zrevrangezrevrange 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ò)展才能使用

相關(guān)文章

  • PHP過濾★等特殊符號的正則

    PHP過濾★等特殊符號的正則

    過濾特殊符號的方法有很多,下面為大家介紹下使用正則來實(shí)現(xiàn)下,希望對大家有所幫助
    2014-01-01
  • 簡單了解PHP編程中數(shù)組的指針的使用

    簡單了解PHP編程中數(shù)組的指針的使用

    這篇文章主要介紹了簡單了解PHP編程中數(shù)組的指針的使用,這里著重討論了賦值時(shí)指針的指向等使用時(shí)值得注意的地方,需要的朋友可以參考下
    2015-11-11
  • PHP+MariaDB數(shù)據(jù)庫操作基本技巧備忘總結(jié)

    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-05
  • PHP 中關(guān)于ord($str)&gt;0x80的詳細(xì)說明

    PHP 中關(guān)于ord($str)&gt;0x80的詳細(xì)說明

    為了識別雙字節(jié)的字符,比如漢字或日文韓文等都是占兩字節(jié)的,每字節(jié)高位為1,而一般西文字符只有一個(gè)字節(jié),七位有效編碼,高位為0而0x80對應(yīng)的二進(jìn)制代碼為1000 0000,最高位為一,代表漢字.漢字編碼格式通稱為10格式. 一個(gè)漢字占2字節(jié),但只代表一個(gè)字符
    2012-09-09
  • PHP 得到根目錄的 __FILE__ 常量

    PHP 得到根目錄的 __FILE__ 常量

    PHP 的 __FILE__ 常量(如何得到根目錄)
    2008-07-07
  • 探討GDFONTPATH能否被winxp下的php支持

    探討GDFONTPATH能否被winxp下的php支持

    本篇文章是對關(guān)于GDFONTPATH能否被winxp下的php支持進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下
    2013-06-06
  • php對象和數(shù)組相互轉(zhuǎn)換的方法

    php對象和數(shù)組相互轉(zhuǎn)換的方法

    這篇文章主要介紹了php對象和數(shù)組相互轉(zhuǎn)換的方法,通過兩個(gè)自定義函數(shù)實(shí)現(xiàn)對象與數(shù)組的相互轉(zhuǎn)換功能,非常簡單實(shí)用,需要的朋友可以參考下
    2015-05-05
  • PHP內(nèi)置加密函數(shù)詳解

    PHP內(nèi)置加密函數(shù)詳解

    在網(wǎng)站的開發(fā)過程中,常常需要對部分?jǐn)?shù)據(jù)(如用戶密碼)進(jìn)行加密,本文主要介紹PHP的幾個(gè)常見的加密函數(shù)
    2016-11-11
  • 常見PHP數(shù)據(jù)庫解決方案分析介紹

    常見PHP數(shù)據(jù)庫解決方案分析介紹

    您可以用很多的方式創(chuàng)建PHP數(shù)據(jù)庫設(shè)計(jì)、數(shù)據(jù)庫訪問和基于數(shù)據(jù)庫的 PHP 業(yè)務(wù)邏輯代碼,但最終一般以錯(cuò)誤告終。本文說明了數(shù)據(jù)庫設(shè)計(jì)和訪問數(shù)據(jù)庫的PHP代碼中出現(xiàn)的常見問題,以及在遇到這些問題時(shí)如何修復(fù)它們。
    2015-09-09
  • php操作Redis數(shù)據(jù)庫基本示例【安裝、連接、設(shè)置、查詢、斷開】

    php操作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

最新評論