1. 程式人生 > 其它 >thinkphp6:訪問redis6(thinkphp 6.0.9/php 8.0.14)

thinkphp6:訪問redis6(thinkphp 6.0.9/php 8.0.14)

一,在.env中配置redis資訊:

[REDIS0]
TYPE = redis
HOST = 127.0.0.1
PORT = 6379
PASSWORD =

說明:劉巨集締的架構森林是一個專注架構的部落格,地址:https://www.cnblogs.com/architectforest

對應的原始碼可以訪問這裡獲取:https://github.com/liuhongdi/
或:https://gitee.com/liuhongdi

說明:作者:劉巨集締 郵箱: [email protected]

二,編寫程式碼訪問redis

1,在config/cache新增對redis0的訪問: cache.php
<?php
 
// +---------------------------------------------------------------------- // | 快取設定 // +---------------------------------------------------------------------- return [ // 預設快取驅動 'default' => env('cache.driver', 'file'), // 快取連線方式配置 'stores' => [ 'file' => [ // 驅動方式
'type' => 'File', // 快取儲存目錄 'path' => '', // 快取字首 'prefix' => '', // 快取有效期 0表示永久快取 'expire' => 0, // 快取標籤字首 'tag_prefix' => 'tag:', // 序列化機制 例如 ['serialize', 'unserialize']
'serialize' => [], ], // 更多的快取連線 // 更多的快取連線 'redis0' => [ 'type' => env('redis0.type', 'redis'), 'host' => env('redis0.host', '127.0.0.1'), 'port' => env('redis0.port', '6379'), 'password' => env('redis0.password', ''), 'select' => '0', // 全域性快取有效期(0為永久有效) 'expire' => 0, // 快取字首 'prefix' => '', 'timeout' => 0, ], ], ];
2,使用redis 新增controller
liuhongdi@lhdpc:/data/php/admapi$ php think make:controller Article
Controller:app\controller\Article created successfully.
增加程式碼:
<?php
declare (strict_types = 1);
 
namespace app\controller;
 
use app\result\Result;
use think\Request;
use think\facade\Cache;
 
class Article
{
    /**
     * 在redis寫入並讀取資料
     *
     * @return \think\Response
     */
    public function index()
    {
        Cache::store('redis0')->set('name0','value1234',3600);
        $value0 = Cache::store('redis0')->get("name0");
 
        $data = ["name0"=>$value0];
        return Result::Success($data);
    }
}
 
3,result程式碼: Result.php
<?php
 
namespace app\result;
 
use think\response\Json;
 
class Result {
    //success
    static public function Success($data):Json {
        $rs = [
            'code'=>0,
            'msg'=>"success",
            'data'=>$data,
        ];
        return json($rs);
    }
    //error
    static public function Error($code,$msg):Json {
        $rs = [
            'code'=>$code,
            'msg'=>$msg,
            'data'=>"",
        ];
        return json($rs);
    }
}

三,遇到報錯:

throw new \BadFunctionCallException('not support: redis');
thinkphp丟擲異常: not support: redis 說明沒有安裝php訪問redis的驅動模組, 參考這一篇安裝即可:
https://www.cnblogs.com/architectforest/p/15737959.html

四,測試效果

訪問:
http://192.168.219.6:8000/article/index
返回如圖:

五,檢視thinkphp和php的版本:

root@lhdpc:~# php --version
PHP 8.0.14 (cli) (built: Dec 23 2021 11:52:42) ( NTS )
Copyright (c) The PHP Group
Zend Engine v4.0.14, Copyright (c) Zend Technologies
    with Zend OPcache v8.0.14, Copyright (c), by Zend Technologies
root@lhdpc:~# cd /data/php/admapi/
root@lhdpc:/data/php/admapi# php think version
v6.0.9