增加路由解析缓存功能

This commit is contained in:
yunwuxin
2018-05-17 18:07:56 +08:00
parent de81a830d0
commit b229e2de33
2 changed files with 206 additions and 155 deletions

View File

@@ -835,6 +835,15 @@ class Route
*/
public static function check($request, $url, $depr = '/', $checkDomain = false)
{
//检查解析缓存
if (Config::get('route_check_cache')) {
$key = self::getCheckCacheKey($request);
if (Cache::has($key)) {
list($rule, $route, $pathinfo, $option, $matches) = Cache::get($key);
return self::parseRule($rule, $route, $pathinfo, $option, $matches, true);
}
}
// 分隔符替换 确保路由定义使用统一的分隔符
$url = str_replace($depr, '|', $url);
@@ -1375,11 +1384,23 @@ class Route
* @param string $pathinfo URL地址
* @param array $option 路由参数
* @param array $matches 匹配的变量
* @param bool $fromCache 通过缓存解析
* @return array
*/
private static function parseRule($rule, $route, $pathinfo, $option = [], $matches = [])
private static function parseRule($rule, $route, $pathinfo, $option = [], $matches = [], $fromCache = false)
{
$request = Request::instance();
//保存解析缓存
if (Config::get('route_check_cache') && !$fromCache) {
try {
$key = self::getCheckCacheKey($request);
Cache::tag('route_check')->set($key, [$rule, $route, $pathinfo, $option, $matches]);
} catch (\Exception $e) {
}
}
// 解析路由规则
if ($rule) {
$rule = explode('/', $rule);
@@ -1601,4 +1622,25 @@ class Route
}
return $var;
}
/**
* 获取路由解析缓存的key
* @param Request $request
* @return string
*/
private static function getCheckCacheKey(Request $request)
{
static $key;
if (empty($key)) {
if ($callback = Config::get('route_check_cache_key')) {
$key = call_user_func($callback, $request);
} else {
$key = "{$request->host(true)}|{$request->method()}|{$request->path()}";
}
}
return $key;
}
}

View File

@@ -10,8 +10,10 @@
// +----------------------------------------------------------------------
namespace think\console\command;
use think\Cache;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
@@ -22,6 +24,7 @@ class Clear extends Command
// 指令配置
$this
->setName('clear')
->addArgument('type', Argument::OPTIONAL, 'type to clear', null)
->addOption('path', 'd', Option::VALUE_OPTIONAL, 'path to clear', null)
->setDescription('Clear runtime file');
}
@@ -30,9 +33,15 @@ class Clear extends Command
{
$path = $input->getOption('path') ?: RUNTIME_PATH;
$type = $input->getArgument('type');
if ($type == 'route') {
Cache::clear('route_check');
} else {
if (is_dir($path)) {
$this->clearPath($path);
}
}
$output->writeln("<info>Clear Successed</info>");
}