美文网首页
thinkphp5配置redis及使用 - 2019-07-17

thinkphp5配置redis及使用 - 2019-07-17

作者: 一位先生_ | 来源:发表于2019-07-17 17:56 被阅读0次

config.php中进行如下设置 (//当前默认使用缓存为file)

// +----------------------------------------------------------------------

// | 缓存设置

// +----------------------------------------------------------------------

'cache'                  => [

     // 选择模式

    'type'  =>  'complex',

        // 默认使用的缓存-文件缓存

        'default'  =>  [

            // 驱动方式

            'type'  => 'File',

            // 缓存保存目录

            'path'  => CACHE_PATH,

        ],

        // redis缓存

        'redis'  =>  [

            // 驱动方式

            'type'  => 'redis',

            // 服务器地址

            'host'      => '192.168.33.10',

            'password' => '',

        ],

],

控制器中代码操作:

namespace app\index\controller;

use think\Controller;

use think\Db;

use think\Cache;

class Index extends Controller

{

    public function index()

{

        if(empty(Cache::store('redis')->get('data'))){

            $data = DB::name('user')->limit(10)->select();

            Cache::store('redis')->set('data', $data,20);

        }

        $users = Cache::store('redis')->get('data');

        if($users){

            echo json_encode(['code'=>200,'status'=>1,'msg'=>'成功','data'=>$users]);

        }else{

            echo json_encode(['code'=>200,'status'=>0,'msg'=>'失败','data'=>[]]);

        }

}

}

备注:

如果访问接口的时候报出:Non-static method think\Cache::store() should not be called statically

说明use hink\Cache 存在问题,路径不对

需要修改为:

use think\Facade\Cache;

然后完美解决。

相关文章

网友评论

      本文标题:thinkphp5配置redis及使用 - 2019-07-17

      本文链接:https://www.haomeiwen.com/subject/exuclctx.html