完成自动缓存功能集成;

This commit is contained in:
2022-04-20 15:00:23 +08:00
parent 07b2dda529
commit cc29874a16
10 changed files with 238 additions and 57 deletions

View File

@@ -3,6 +3,7 @@ COVER_THEME=index
[APP]
DEFAULT_TIMEZONE=Asia/Shanghai
AUTO_CACHE_LOG=false
[DATABASE]
TYPE=mysql

View File

@@ -34,6 +34,7 @@ class Index extends AdminController
$quicks = SystemQuick::field('id,title,icon,href')
->where(['status' => 1])
->order('sort', 'desc')
->autoCache('welcome_list')
->limit(8)
->select();
$this->assign('quicks', $quicks);

View File

@@ -20,6 +20,13 @@ class SystemAdmin extends TimeModel
protected $deleteTime = 'delete_time';
public static $autoCache = [
[
'name' => 'info',
'field' => 'id'
]
];
public function getAuthList()
{
$list = (new SystemAuth())
@@ -27,5 +34,4 @@ class SystemAdmin extends TimeModel
->column('title', 'id');
return $list;
}
}
}

View File

@@ -44,6 +44,4 @@ class SystemNode extends TimeModel
}
return $newList;
}
}
}

View File

@@ -20,4 +20,9 @@ class SystemQuick extends TimeModel
protected $deleteTime = 'delete_time';
}
public static $autoCache = [
[
'name' => 'welcome_list'
]
];
}

View File

@@ -0,0 +1,100 @@
<?php
namespace app\common\model;
use think\facade\Cache;
use think\facade\Env;
use think\facade\Log;
use think\Model;
use think\helper\Str;
class BaseModel extends Model
{
/**
* 自动清除的缓存值
*
* [
* 'name'=>'',
* 'type'=>'', // tag/key
* 'field'=>'' // 为空则不做拼接
* ]
*
* @var array
*/
public static $autoCache = [];
public static function onAfterWrite($model)
{
static::autoRemoveCache($model);
}
public static function onAfterDelete($model)
{
static::autoRemoveCache($model);
}
public static function onAfterRestore($model)
{
static::autoRemoveCache($model);
}
public static function autoRemoveCache($model)
{
static::$autoCache[] = [
'name' => 'table',
'type' => 'tag'
];
static::$autoCache[] = [
'name' => 'read',
'field' => 'id'
];
foreach (static::$autoCache as $cache_item) {
$type = $cache_item['type'] ?? 'key';
$field = $cache_item['field'] ?? '';
$cache_key = $cache_item['name'] ?? '';
if (empty($cache_key)) {
continue;
}
$cache_key = Str::snake($model->getName()) . '_' . $cache_key;
if (!empty($field) && !is_null($model->$field)) {
// 用字段新的值拼接key
$cache_key_attr = $cache_key . '_' . $model->getAttr($field);
static::doRemoveCache($type, $cache_key_attr);
// 用字段旧的值拼接key
$cache_key_original = $cache_key . '_' . $model->getOrigin($field);
if ($cache_key_original != $cache_key_attr) {
static::doRemoveCache($type, $cache_key_original);
}
} else {
static::doRemoveCache($type, $cache_key);
}
}
}
protected static function doRemoveCache($type, $cache_key)
{
if (Env::get('app.auto_cache_log')) {
Log::debug("清除 ORM 自动缓存 {$type}:{$cache_key}");
}
if ($type == 'key') {
Cache::delete($cache_key);
} else {
Cache::tag($cache_key)->clear();
}
}
public static function getClassNameKey()
{
return str_replace('\\', '_', static::class);
}
}

View File

@@ -14,7 +14,6 @@
namespace app\common\model;
use think\Model;
use think\model\concern\SoftDelete;
/**
@@ -22,7 +21,7 @@ use think\model\concern\SoftDelete;
* Class TimeModel
* @package app\common\model
*/
class TimeModel extends Model
class TimeModel extends BaseModel
{
/**
@@ -47,9 +46,8 @@ class TimeModel extends Model
* 软删除
*/
use SoftDelete;
protected $deleteTime = 'delete_time';
protected $defaultSoftDelete = 0;
}
}

View File

@@ -0,0 +1,64 @@
<?php
namespace app\common\provider\db;
use think\db\Query as DbQuery;
use think\facade\Env;
use think\facade\Log;
use think\helper\Str;
class Query extends DbQuery
{
/**
* autoCache 自动生成缓存
*
* @param null|string $key
* @param null|string|int $field_key_value
* @param null|string $tag
* @param null|string|int $field_tag_value
* @return void
*/
public function autoCache($key = null, $field_key_value = null, $tag = null, $field_tag_value = null)
{
$table_name = Str::snake($this->getName());
if (is_null($key)) {
$key = $this->getOptionsMd5();
}
if (!is_null($field_key_value)) {
$key = $key . '_' . $field_key_value;
}
$key = $table_name . '_' . $key;
if (!is_null($tag)) {
if (!is_null($field_key_value)) {
$tag = $tag . '_' . $field_tag_value;
}
$tag = $table_name . '_' . $tag;
}
if(Env::get('app.auto_cache_log')){
Log::debug('use auto cache:' . $key);
Log::debug('use auto cache tag:' . $tag);
}
$this->cache($key, null, $tag);
return $this;
}
public function getOptionsMd5()
{
$options = $this->getOptions();
// TODO:支持获取回调函数的设置
return md5(json_encode($options));
}
}

View File

@@ -39,7 +39,7 @@ class AuthService
'system_admin' => 'system_admin', // 用户表
'system_auth' => 'system_auth', // 权限表
'system_node' => 'system_node', // 节点表
'system_auth_node' => 'system_auth_node',// 权限-节点表
'system_auth_node' => 'system_auth_node', // 权限-节点表
];
/**
@@ -140,11 +140,12 @@ class AuthService
public function getAdminNode()
{
$nodeList = [];
$adminInfo = Db::name($this->config['system_admin'])
->where([
'id' => $this->adminId,
'status' => 1,
])->find();
$adminInfo = $this->getAdminInfo();
if ($adminInfo['status'] != 1) {
return $nodeList;
}
if (!empty($adminInfo) && !empty($adminInfo['auth_ids'])) {
$buildAuthSql = Db::name($this->config['system_auth'])
->distinct(true)
@@ -170,9 +171,11 @@ class AuthService
* @return array
* @author zhongshaofa <shaofa.zhong@happy-seed.com>
*/
public function getNodeList(){
public function getNodeList()
{
return Db::name($this->config['system_node'])
->column('id,node,title,type,is_auth','node');
->autoCache(null, null, 'table')
->column('id,node,title,type,is_auth', 'node');
}
/**
@@ -184,9 +187,11 @@ class AuthService
* @throws \think\db\exception\ModelNotFoundException
* @author zhongshaofa <shaofa.zhong@happy-seed.com>
*/
public function getAdminInfo(){
public function getAdminInfo()
{
return Db::name($this->config['system_admin'])
->where('id', $this->adminId)
->autoCache('info', $this->adminId)
->find();
}
@@ -211,5 +216,4 @@ class AuthService
$node = implode('/', $array);
return $node;
}
}
}

View File

@@ -1,5 +1,6 @@
<?php
use app\common\provider\db\Query;
use think\facade\App;
use think\facade\Env;
@@ -57,45 +58,48 @@ return [
// 开启字段缓存
'fields_cache' => Env::get('database.fields_cache', false),
'query' => Query::class
],
'sqlite' => [
// 数据库类型
'type' => 'sqlite',
// 服务器地址
'hostname' => Env::get('root_path').'ul.db',
// 数据库名
'database' => App::getRootPath().'ul.db',
// 用户名
'username' => Env::get('database.username', ''),
// 密码
'password' => Env::get('database.password', ''),
// 端口
'hostport' => Env::get('database.hostport', '3306'),
// 数据库连接参数
'params' => [],
// 数据库编码默认采用utf8
'charset' => Env::get('database.charset', 'utf8'),
// 数据库表前缀
'prefix' => Env::get('database.prefix', 'ul_'),
// 数据库调试模式
'debug' => Env::get('database.debug', true),
// 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)
'deploy' => 0,
// 数据库读写是否分离 主从式有效
'rw_separate' => false,
// 读写分离后 主服务器数量
'master_num' => 1,
// 指定从服务器序号
'slave_no' => '',
// 是否严格检查字段是否存在
'fields_strict' => true,
// 是否需要进行SQL性能分析
'sql_explain' => false,
// 是否需要断线重连
'break_reconnect' => false,
],
'type' => 'sqlite',
// 服务器地址
'hostname' => Env::get('root_path') . 'ul.db',
// 数据库名
'database' => App::getRootPath() . 'ul.db',
// 用户名
'username' => Env::get('database.username', ''),
// 密码
'password' => Env::get('database.password', ''),
// 端口
'hostport' => Env::get('database.hostport', '3306'),
// 数据库连接参数
'params' => [],
// 数据库编码默认采用utf8
'charset' => Env::get('database.charset', 'utf8'),
// 数据库表前缀
'prefix' => Env::get('database.prefix', 'ul_'),
// 数据库调试模式
'debug' => Env::get('database.debug', true),
// 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)
'deploy' => 0,
// 数据库读写是否分离 主从式有效
'rw_separate' => false,
// 读写分离后 主服务器数量
'master_num' => 1,
// 指定从服务器序号
'slave_no' => '',
// 是否严格检查字段是否存在
'fields_strict' => true,
// 是否需要进行SQL性能分析
'sql_explain' => false,
// 是否需要断线重连
'break_reconnect' => false,
'query' => Query::class
],
// 更多的数据库配置信息