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;
然后完美解决。
网友评论