~~~
//實例化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 的值
}
}
~~~