~~~
//实例化redis 推荐使用cache.php 连接redis
$redis = new Redis();
//连接
$redis->connect('127.0.0.1', 6379);
//检测是否连接成功
echo "Server is running: " . $redis->ping();
// 输出结果 Server is running: +PONG
~~~
~~~
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// +----------------------------------------------------------------------
// | 缓存设置
// +----------------------------------------------------------------------
/**
修改cache.php
**/
return [
// 驱动方式
'type' => 'complex',
// 默认
'default' => [
// 驱动方式
'type' => 'File',
// 缓存保存目录
'path' => '',
// 缓存前缀
'prefix' => '',
// 缓存有效期 0表示永久缓存
'expire' => 0,
],
// 文件
'file' => [
// 驱动方式
'type' => 'File',
// 缓存保存目录
'path' => '',
// 缓存前缀
'prefix' => '',
// 缓存有效期 0表示永久缓存
'expire' => 0,
],
// redis
'redis' => [
'type' => 'redis',
'host' => '127.0.0.1',
'port' => '6379',
'password' => '',
// 全局缓存有效期(0为永久有效)
'expire' => 0,
// 缓存前缀
'prefix' => '',
],
];
~~~
~~~
<?php
namespace app\index\controller;
use think\cache\driver\Redis; //引入Redis
class Index
{
public function index()
{
// 读取redis的配置
$redis=new Redis(config('cache.redis')); //实例化redis
$redis->set('test:str0','sss','100'); //key=>db0下test文件夹下str0 value 有效时间
$redis->setnx('test:str4', 'sss')); //只有key不存在的情况下设置成功,并且无法设置有效时间
$redis->get('test:str0'); //获取test:str0 的值
}
}
~~~