From c38fb6ac4cde6974b3c419dcc38dfebda42d4313 Mon Sep 17 00:00:00 2001 From: whwyy Date: Wed, 24 Jun 2026 20:11:11 +0800 Subject: [PATCH] eee --- Container.php | 69 +++++++++++++++++++++++++++++++++++++++++++++++++++ Scanner.php | 3 +++ 2 files changed, 72 insertions(+) diff --git a/Container.php b/Container.php index 76956c1..ee9eae3 100644 --- a/Container.php +++ b/Container.php @@ -207,6 +207,75 @@ class Container implements ContainerInterface } + /** + * 清理所有非基础设施类的单例引用,释放 Swoole 常驻进程中的内存 + * 保留框架核心类(Kiri、Database、Psr、Symfony)的单例 + * 应在请求/任务完成后调用,防止单例映射无限增长 + * @return void + */ + public function clearNonInfrastructure(): void + { + $keepPrefixes = [ + ContainerInterface::class, + 'Kiri\\', 'Database\\', 'Psr\\', 'Symfony\\', + 'Swoole\\', 'MongoDB\\', + ]; + + foreach (array_keys($this->_singletons) as $className) { + $shouldKeep = false; + foreach ($keepPrefixes as $prefix) { + if (str_starts_with($className, $prefix)) { + $shouldKeep = true; + break; + } + } + if (!$shouldKeep) { + unset($this->_singletons[$className]); + } + } + + foreach (array_keys($this->_reflection) as $className) { + $shouldKeep = false; + foreach ($keepPrefixes as $prefix) { + if (str_starts_with($className, $prefix)) { + $shouldKeep = true; + break; + } + } + if (!$shouldKeep) { + unset($this->_reflection[$className]); + } + } + + foreach (array_keys($this->_parameters) as $className) { + $shouldKeep = false; + foreach ($keepPrefixes as $prefix) { + if (str_starts_with($className, $prefix)) { + $shouldKeep = true; + break; + } + } + if (!$shouldKeep) { + unset($this->_parameters[$className]); + } + } + } + + + /** + * 获取当前单例缓存统计信息,用于内存监控 + * @return array{singletons: int, reflections: int, params: int} + */ + public function getMemoryStats(): array + { + return [ + 'singletons' => count($this->_singletons), + 'reflections' => count($this->_reflection), + 'params' => count($this->_parameters), + ]; + } + + /** * @param string $className * @param array $construct diff --git a/Scanner.php b/Scanner.php index 7b1bae6..6e58b93 100644 --- a/Scanner.php +++ b/Scanner.php @@ -589,6 +589,9 @@ class Scanner extends Component if (method_exists($this->container, 'forgetClass')) { $this->container->forgetClass($class); } + if (class_exists(\Kiri\Router\Annotate\DeferRegistry::class)) { + \Kiri\Router\Annotate\DeferRegistry::removeClass($class); + } } } }