如果TP5想要使用redis缓存,首先要修改config中的缓存设置;
'cache' => [
// 使用复合缓存类型
'type' => 'complex',
// 默认使用的缓存
'default' => [
// 驱动方式
'type' => 'File',
// 缓存保存目录
'path' => CACHE_PATH,
],
'file' => [
// 驱动方式
'type' => 'File',
// 缓存保存目录
'path' => CACHE_PATH,
//缓存前缀
'prefix' => '',
//缓存有效期 0表示永久缓存
'expire' => 0,
],
// redis缓存
'redis' => [
// 驱动方式
'type' => 'redis',
// 服务器地址
'host' => '127.0.0.1',
'port' => 6379,
'expire' => 0 ,
],
],
如果想要同时使用多个缓存类型进行操作的话,可以设置成我的这种,
cache.type 配置为complex之后,就可以缓存多个缓存类型和缓存配置,每个缓存配置的方法和之前一 样,并且你可以给相同类型的缓存类型(使用不同的缓存标识)配置不同的缓存配置参数。
如果想要使用redis缓存 操作的话,可以使用:
Cache::store('redis')->set('id')
Cache::get('id')
使用别的缓存操作的话也是如此,就是把Cache::store括号中的缓存标识,换成你想使用的缓存表示就可以;
具体如何操作,请去看ThinkPHP5.0完全手册 -> 杂项 -> 缓存
下面就是在TP5中controller的操作,
<?php
namespace app\index\controller;
use think\Controller;
use think\Cache;
class Test extends Controller
{
private $expire = 60; //缓存时间(单位:秒)
private $redis;
public function _initialize()
{
$this->redis = Cache::store('redis')->handler(); //返回redis对象
}
public function index(){
//将哈希表 key 中的字段 field 的值设为 value
//123456是key,'yzm'是field,4566是value
$this->redis->hset('123456','yzm','4566');
//设置过期时间,时间一到,此条记录就会消失
$this->redis->expire('123456',$this->expire);
}
}
这里面用到了redis中的hash表,
hset是redis中的HASH命令:
HSET key field value
将哈希表 key 中的字段 field 的值设为 value 。
expire是redis中的KEYS命令:
EXPIRE key seconds
为给定 key 设置过期时间,以秒计。
更多Redis命令,请去https://www.runoob.com/redis/redis-commands.html
最后运行这个方法,在redis的hash表中就会出现你存进去的这条数据,在你设置的过期时间到了之后这一条数据就会消失