ThinkPHP5配置redis缓存

thinkphp采用cache类提供缓存功能支持,采用驱动方式,在使用缓存之前需要进行初始化操作。支持的缓存类型包括file、memcache、wincache、sqlite、redis和xcache等,

默认情况下是file类型,配置redis缓存可以单一配置redis也可以同时使用多个缓存类型。配置方式分别如下: 一、仅配置redis缓存,在配置文件(app
/config.php)中修改缓存设置如下:
'cache'                  => [
    // 驱动方式
    // 'type'   => 'File',
    // 缓存保存目录
    // 'path'   => CACHE_PATH,
    // 缓存前缀
    // 'prefix' => '',
    // 缓存有效期 0表示永久缓存
    // 'expire' => 0,
    'redis'   =>  [
        // 驱动方式
        'type'   => 'redis',
        // 服务器地址
        'host'   => '192.168.1.xxx',  //redis服务器ip
    ],

],
 
 

  

 二、配置多个缓存类型,使用符合缓存类型,配置方式如下:

'cache' =>  [
    // 使用复合缓存类型
    'type'  =>  'complex',
    // 默认使用的缓存
    'default'   =>  [
        // 驱动方式
        'type'   => 'File',
        // 缓存保存目录
        'path'   => CACHE_PATH,
    ],
    // 文件缓存
    'file'   =>  [
        // 驱动方式
        'type'   => 'file',
        // 设置不同的缓存保存目录
        'path'   => RUNTIME_PATH . 'file/',
    ],
    // redis缓存
    'redis'   =>  [
        // 驱动方式
        'type'   => 'redis',
        // 服务器地址
        'host'   => '192.168.1.xxx',  //redis服务器ip
    ],
],
 
 

  

 使用符合缓存类型时,需要根据需要使用store方法切换缓存。 当使用
Cache::set('name', 'value');

Cache::get('name');
 
 

  

 的时候,使用的是default缓存标识的缓存配置。 如果需要切换到其它的缓存标识操作,可以使用:
// 切换到file操作

Cache::store('file')->set('name','value');

Cache::get('name');

// 切换到redis操作

Cache::store('redis')->set('name','value');

Cache::get('name');
 
 

  

 比如,查询一篇文章时首先从redis中查询,若未查到信息则从数据库中查询出结果,并存储到redis中。
$article =Cache::store('redis')->get('artcicle'.$id);
if (!$article) {
  $article = Db::name('article')->where('status',1)->cache(true)->find($id);
  Cache::store('redis')->set('article'.$id,$article);
}
 
 

  

猜你喜欢

转载自www.cnblogs.com/qhorse/p/9542871.html