mirror of https://gitee.com/karson/fastadmin.git
Pre Merge pull request !517 from 高级CV工程师/1.x-dev
commit
4dabece96c
|
|
@ -0,0 +1,75 @@
|
|||
<?php
|
||||
|
||||
namespace app\common\behavior;
|
||||
|
||||
use think\Cache;
|
||||
use think\Config;
|
||||
use think\Log;
|
||||
|
||||
class RedisSiteConfig
|
||||
{
|
||||
public function appInit()
|
||||
{
|
||||
if (self::isEnableRedis()) {
|
||||
// 从 Redis 缓存加载配置
|
||||
Config::set([
|
||||
'site' => self::all()
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
public static function isEnableRedis(): bool
|
||||
{
|
||||
return strtolower(Config::get('cache.type')) === 'redis';
|
||||
}
|
||||
|
||||
public static function getCacheKey(): string
|
||||
{
|
||||
// 缓存键名,根据目录结构哈希,确保不同项目配置不冲突
|
||||
return 'fastadmin:site_config:' . md5(__DIR__);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取全部 site 配置
|
||||
*/
|
||||
public static function all(): array
|
||||
{
|
||||
try {
|
||||
return Cache::remember(self::getCacheKey(), self::loadFromDb(), 0);
|
||||
} catch (\Throwable $e) {
|
||||
// Redis 挂了也不能影响站点
|
||||
Log::error('SiteConfig cache error: ' . $e->getMessage());
|
||||
return self::loadFromDb();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 强制刷新缓存
|
||||
*/
|
||||
public static function refresh(): void
|
||||
{
|
||||
Cache::rm(self::getCacheKey());
|
||||
}
|
||||
|
||||
/**
|
||||
* 从数据库加载 site 配置
|
||||
*/
|
||||
protected static function loadFromDb(): array
|
||||
{
|
||||
$config = [];
|
||||
$configList = \app\common\model\Config::all();
|
||||
foreach ($configList as $k => $v) {
|
||||
$value = $v->toArray();
|
||||
if (in_array($value['type'], ['selects', 'checkbox', 'images', 'files'])) {
|
||||
$value['value'] = explode(',', $value['value']);
|
||||
}
|
||||
if ($value['type'] == 'array') {
|
||||
$value['value'] = (array)json_decode($value['value'], true);
|
||||
}
|
||||
$config[$value['name']] = $value['value'];
|
||||
}
|
||||
|
||||
return $config;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -206,6 +206,13 @@ class Config extends Model
|
|||
if (!\app\admin\library\Auth::instance()->check('general/config/edit')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (\app\common\behavior\RedisSiteConfig::isEnableRedis()) {
|
||||
// 刷新 Redis 缓存
|
||||
\app\common\behavior\RedisSiteConfig::refresh();
|
||||
return true;
|
||||
}
|
||||
|
||||
$config = [];
|
||||
$configList = self::all();
|
||||
foreach ($configList as $k => $v) {
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@ return [
|
|||
// 应用初始化
|
||||
'app_init' => [
|
||||
'app\\common\\behavior\\Common',
|
||||
'app\\common\\behavior\\RedisSiteConfig',
|
||||
],
|
||||
// 应用开始
|
||||
'app_begin' => [],
|
||||
|
|
|
|||
Loading…
Reference in New Issue