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

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;

然后完美解决。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容