安装redis指定版本
composer require easyswoole/redis:^1.3
redis配置,dev.php
<?php
use EasySwoole\Log\LoggerInterface;
return [
'SERVER_NAME' => "EasySwoole",
'MAIN_SERVER' => [
'LISTEN_ADDRESS' => '0.0.0.0',
'PORT' => 9503,
'SERVER_TYPE' => EASYSWOOLE_WEB_SERVER, //可选为 EASYSWOOLE_SERVER EASYSWOOLE_WEB_SERVER EASYSWOOLE_WEB_SOCKET_SERVER
'SOCK_TYPE' => SWOOLE_TCP,
'RUN_MODEL' => SWOOLE_PROCESS,
'SETTING' => [
'worker_num' => 8,
'reload_async' => true,
'max_wait_time' => 3
],
'TASK' => [
'workerNum' => 4,
'maxRunningNum' => 128,
'timeout' => 15
]
],
"LOG" => [
'dir' => null,
'level' => LoggerInterface::LOG_LEVEL_DEBUG,
'handler' => null,
'logConsole' => true,
'displayConsole' => true,
'ignoreCategory' => []
],
'TEMP_DIR' => null,
// 添加 Redis 及对应的连接池配置
/*################ REDIS CONFIG ##################*/
'REDIS' => [
'host' => '127.0.0.1', // Redis 地址
'port' => '6379', // Redis 端口
'auth' => '', // Redis 密码
'timeout' => 3.0, // Redis 操作超时时间
'reconnectTimes' => 3, // Redis 自动重连次数
'db' => 0, // Redis 库
],
];
EasySwooleEvent.php,加入预加载
public static function initialize()
{
date_default_timezone_set('Asia/Shanghai');
$rdConfig = new RedisConfig(Config::getInstance()->getConf('REDIS'));
RedisPool::getInstance()->register($rdConfig);
}
控制器使用
public function getOne()
{
$param = ContextManager::getInstance()->get('param');
$redis = RedisPool::defer();
//redis 操作
$redisData = $redis->get($this->key.$param['id']);
if ($redisData) {
$this->writeJson(Status::CODE_OK, json_decode($redisData, true), "获取数据成功.");
return false;
}
$model = new StudentModel();
try {
$info = $model->where('id', $param['id'])->get();
} catch (Exception|\EasySwoole\ORM\Exception\Exception|\Throwable $e) {
$this->writeJson(Status::CODE_BAD_REQUEST, [], $e->getMessage());
return false;
}
if (!$info) {
$this->writeJson(400, [], '该数据不存在');
return false;
}
$redis->set($this->key.$param['id'], json_encode($info, JSON_UNESCAPED_UNICODE), $this->time);
$this->writeJson(Status::CODE_OK, $info, "获取数据成功.");
}