使用composer
安装"predis/predis"
完毕,.env
加入如下配置:
[REDIS]
HOST=127.0.0.1
scheme=tcp
PORT=6379
CACHE_DB=0
TOKEN_DB=1
PASSWORD=admin
config
下redis
配置文件redis.php
<?php
//Redis配置文件
return [
'scheme' => env('redis.scheme', 'tcp'),
'host' => env('redis.host', '127.0.0.1'),
'port' => env('redis.port', '6379'),
'token' => env('redis.token_db', '1'), // token数据库:默认0~15个
'cache' => env('redis.cache_db', '0'), // 缓存数据库
'password' => env('redis.password', ''),
];
直接使用
use Predis\Client;
$redis = new Client([
'scheme' => config('redis.scheme'),
'host' => config('redis.host'),
'port' => config('redis.port'),
'cache' => config('redis.cache'),
'password' => config('redis.password'),
]);
print_r($redis->set('test','123'));
打印结果
Predis\Response\Status Object ( [payload:Predis\Response\Status:private] => OK )
封装服务类使用
<?php
// +----------------------------------------------------------------------
// |Redis 服务类
// +----------------------------------------------------------------------
// | Author: DragonersLi
// +----------------------------------------------------------------------
// | Date: 2020-07-24
// +----------------------------------------------------------------------
namespace app\common\service;
use Predis\Client;
class RedisService
{
public function __construct() {}
/**
* 静态调用redis
*/
public static function select($db = 0){
return new Client([
'scheme' => config('redis.scheme'),
'host' => config('redis.host'),
'port' => config('redis.port'),
'database' => $db,//config('redis.database'),
'password' => config('redis.password')
]);
}
}
RedisService::select(config('redis.cache'))->set('a',123);
网友评论