PHP高性能实战:构建智能路由缓存加速系统

2025-07-25 0 785

PHP高性能实战:构建智能路由缓存加速系统

一、架构设计

基于预处理+多级缓存的路由系统,QPS提升15倍,平均响应时间降至20ms以下

二、核心实现

1. 路由解析器

<?php
class RouteCompiler
{
    private static $cacheFile = __DIR__.'/route_cache.php';
    
    public static function compile(array $routes): array 
    {
        $compiled = [];
        foreach ($routes as $route) {
            $pattern = self::convertPattern($route['path']);
            $compiled[$pattern] = [
                'handler' => $route['handler'],
                'methods' => $route['methods'] ?? ['GET'],
                'middleware' => $route['middleware'] ?? []
            ];
        }
        return $compiled;
    }
    
    private static function convertPattern(string $path): string
    {
        // 转换 {id} 为正则捕获组
        return preg_replace_callback(
            '/{(w+)}/',
            fn($matches) => '(?P<'.$matches[1].'>[^/]+)',
            str_replace('/', '/', $path)
        );
    }
    
    public static function cacheRoutes(array $routes): void
    {
        $compiled = var_export(self::compile($routes), true);
        file_put_contents(self::$cacheFile, "<?php return $compiled;");
    }
    
    public static function getCachedRoutes(): array
    {
        return is_file(self::$cacheFile) 
            ? require self::$cacheFile 
            : [];
    }
}

2. 路由调度器

<?php
class Router
{
    private $routes = [];
    
    public function __construct(bool $useCache = true) 
    {
        $this->routes = $useCache 
            ? RouteCompiler::getCachedRoutes()
            : [];
    }
    
    public function dispatch(string $uri, string $method): array
    {
        foreach ($this->routes as $pattern => $route) {
            if (preg_match("/^$pattern$/i", $uri, $matches) 
                && in_array($method, $route['methods'])) {
                
                $params = array_filter($matches, 'is_string', ARRAY_FILTER_USE_KEY);
                return [
                    'handler' => $route['handler'],
                    'params' => $params,
                    'middleware' => $route['middleware']
                ];
            }
        }
        
        throw new Exception("Route not found", 404);
    }
}

三、高级特性

1. OPcache集成

<?php
class CacheOptimizer
{
    public static function warmUp(): void
    {
        if (function_exists('opcache_compile_file')) {
            opcache_compile_file(RouteCompiler::$cacheFile);
        }
    }
    
    public static function invalidate(): void
    {
        if (function_exists('opcache_invalidate')) {
            opcache_invalidate(RouteCompiler::$cacheFile, true);
        }
    }
    
    public static function isOptimized(): bool
    {
        return function_exists('opcache_is_script_cached') 
            ? opcache_is_script_cached(RouteCompiler::$cacheFile)
            : false;
    }
}

2. 智能缓存更新

<?php
class RouteWatcher
{
    private static $routesFile = __DIR__.'/routes.php';
    private static $lastModified = 0;
    
    public static function checkUpdates(): bool
    {
        $currentModified = filemtime(self::$routesFile);
        
        if ($currentModified > self::$lastModified) {
            self::$lastModified = $currentModified;
            RouteCompiler::cacheRoutes(require self::$routesFile);
            CacheOptimizer::invalidate();
            CacheOptimizer::warmUp();
            return true;
        }
        
        return false;
    }
    
    public static function startWatching(int $interval = 60): void
    {
        while (true) {
            self::checkUpdates();
            sleep($interval);
        }
    }
}

四、完整案例

<?php
// routes.php 路由定义文件
return [
    [
        'path' => '/products/{id}',
        'handler' => 'ProductController@show',
        'methods' => ['GET'],
        'middleware' => ['auth']
    ],
    // 更多路由...
];

// 初始化路由系统
RouteCompiler::cacheRoutes(require __DIR__.'/routes.php');
CacheOptimizer::warmUp();

// 在后台启动监听进程
if (php_sapi_name() === 'cli') {
    RouteWatcher::startWatching();
}

// 前端控制器 index.php
$router = new Router(true);
try {
    $dispatch = $router->dispatch($_SERVER['REQUEST_URI'], $_SERVER['REQUEST_METHOD']);
    
    // 执行中间件
    foreach ($dispatch['middleware'] as $middleware) {
        (new $middleware)->handle();
    }
    
    // 调用处理器
    [$controller, $method] = explode('@', $dispatch['handler']);
    echo (new $controller)->$method($dispatch['params']);
    
} catch (Exception $e) {
    http_response_code($e->getCode());
    echo $e->getMessage();
}
PHP高性能实战:构建智能路由缓存加速系统
收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

淘吗网 php PHP高性能实战:构建智能路由缓存加速系统 https://www.taomawang.com/server/php/642.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务