ThinkPHP框架已经封装好redis驱动,不管是session还是cache都支持redis驱动,下面我们来了解一下在ThinkPHP5.1版本下如何使用redis缓存。
配置:/config/cache.php
return [ // 驱动方式 'type' => 'File', // 缓存保存目录 'path' => '', // 缓存前缀 'prefix' => '', // 缓存有效期 0表示永久缓存 'expire' => 0, 'default' => [ 'type' => 'file', // 全局缓存有效期(0为永久有效) 'expire'=> 0, // 缓存前缀 'prefix'=> 'think', // 缓存目录 'path' => '../runtime/cache/', ], 'redis' => [ 'type' => 'redis', 'host' => '127.0.0.1', // 全局缓存有效期(0为永久有效) 'expire'=> 0, // 缓存前缀 'prefix'=> 'think', ], // 添加更多的缓存类型设置 ];
主要是看redis这一块
赋值
public function redis(){
Cache::store('redis')->set('name','value');
}打印
public function redisShow(){
$name = Cache::store('redis')->get('name');
print_r($name);
}也可以这样使用
$Handler = Cache::store('redis')->handler();
echo $Handler->get('test');注意
// 第一种
$rediss = new \Redis();
$rediss->connect("127.0.0.1","6379");
echo $rediss->get('test');
echo '<br>';
// 第二种
echo Cache::store('redis')->get('test');
//输出:
2020-02-18 15:32:36
2020-02-18 15:32:36
2020-02-18 15:32:11如果想让这两种方式获取的值都一样,必须确保配置一样,特别是prefix前缀
自定义方式
$config = [
'host' => '服务器IP地址',
'port' => Redis端口号,
'password' => 'Redis访问密码',
'select' => 0,
'timeout' => 0,
'expire' => 0,
'persistent' => false,
'prefix' => '',
];
$Redis=new Redis($config);
$Redis->set("test","test");
echo $Redis->get("test");