tp5.1连接redis
时间: 2023-05-23 21:01:20 浏览: 153
可以通过下面的代码来连接 Redis:
```php
// 引入 Redis 类
use think\cache\driver\Redis;
// 设置 Redis 连接配置
$config = [
'host' => '127.0.0.1',
'port' => 6379,
'password' => '密码',
'select' => 0,
'timeout' => 0,
'expire' => 0,
'persistent' => false,
];
// 实例化 Redis 对象
$redis = new Redis($config);
```
以上代码为 ThinkPHP 框架 5.1 的 Redis 连接示例。
相关问题
tp5.1 cache redis剩余时间
要获取TP5.1中Redis缓存的剩余时间,可以使用以下代码:
```php
use think\facade\Cache;
// 获取缓存剩余时间
$ttl = Cache::handler()->ttl('cache_key');
```
其中,`Cache::handler()`可以获取到当前缓存使用的Redis实例,`ttl('cache_key')`则可以获取到`cache_key`缓存的剩余时间,单位为秒。如果返回值为-1,则表示该缓存永久有效;如果返回值为-2,则表示该缓存已过期或不存在。
tp5 redis连接
在TP5中连接Redis的方法如下所示:
```php
use think\cache\driver\Redis;
public function testRedis()
{
try{
$redis = new Redis();
$redis->connect('127.0.0.1', 6379, 2);
$redis->auth('123456');
$res = $redis->ping();
if($res === 'PONG'){
echo '成功';
}
}catch (\Exception $e){
echo '失败';
}
}
```
在这个例子中,我们通过引入`think\cache\driver\Redis`来使用TP5中的Redis缓存驱动。然后,我们创建一个Redis实例,并通过`connect`方法连接到Redis服务器。接着,我们使用`auth`方法进行认证,然后用`ping`方法检测连接状态。如果连接成功,输出"成功";否则,输出"失败"。