use route string to avoid hitting high cardinality path.

This commit is contained in:
reasno 2020-03-21 14:05:47 +08:00
parent f8fac1ab77
commit c480fc9014
5 changed files with 14 additions and 8 deletions

View File

@ -218,7 +218,7 @@ return [
],
];
```
> 本中间件中统计维度包含 `request_status`、`request_path`、`request_method`, 如果您的 `request_path` 包含无限种可能(比如`/users/{id}`),则建议重写本中间件,去掉 `request_path` 维度,否则过高的基数会导致内存溢出。
> 本中间件中统计维度包含 `request_status`、`request_path`、`request_method`。如果您的 `request_path` 过多,则建议重写本中间件,去掉 `request_path` 维度,否则过高的基数会导致内存溢出。
### 自定义使用

View File

@ -34,7 +34,8 @@
"hyperf/di": "Required to use annotations.",
"hyperf/event": "Required to use listeners for default metrics.",
"hyperf/process": "Required to use standalone process, or you have to roll your own",
"hyperf/retry": "Required to use back-off retry implementation."
"hyperf/retry": "Required to use back-off retry implementation.",
"hyperf/http-server": "Required to capture routes in middleware."
},
"autoload": {
"psr-4": {

View File

@ -24,7 +24,6 @@ use Psr\Container\ContainerInterface;
use Psr\EventDispatcher\EventDispatcherInterface;
use Swoole\Server;
use Swoole\Timer;
use Throwable;
use function gc_status;
use function getrusage;
use function memory_get_peak_usage;
@ -159,7 +158,7 @@ class OnWorkerStart implements ListenerInterface
$this->factory->handle();
});
} else {
retry(PHP_INT_MAX, function(){
retry(PHP_INT_MAX, function () {
$this->factory->handle();
}, 100);
}

View File

@ -41,8 +41,6 @@ abstract class PoolWatcher
];
}
abstract protected function getPrefix();
/**
* Periodically scan metrics.
*/
@ -79,4 +77,6 @@ abstract class PoolWatcher
$connectionsInUseGauge->set((float) $pool->getCurrentConnections());
});
}
abstract protected function getPrefix();
}

View File

@ -12,7 +12,7 @@ declare(strict_types=1);
namespace Hyperf\Metric\Middleware;
use Hyperf\Metric\Contract\MetricFactoryInterface;
use Hyperf\HttpServer\Router\Dispatched;
use Hyperf\Metric\Timer;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
@ -29,9 +29,15 @@ class MetricMiddleware implements MiddlewareInterface
*/
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$dispatched = $request->getAttribute(Dispatched::class);
if (! $dispatched) {
$route = $request->getUri()->getPath();
} else {
$route = $dispatched->handler->route;
}
$labels = [
'request_status' => '500', //default to 500 in case uncaught exception occur
'request_path' => $request->getUri()->getPath(),
'request_path' => $route,
'request_method' => $request->getMethod(),
];
$timer = new Timer('http_requests', $labels);