Laravel中GraphQL接口请求频率实战记录
前言
在产品运营阶段,数据埋点至关重要,它能帮助我们追踪用户行为、页面访问量及操作路径,从而辅助产品团队根据用户偏好进行策略调整与推荐优化。同理,在后端服务端开发中,也需要建立完善的“数据埋点”机制,用于记录接口的响应耗时、调用频次及参数分布等关键指标。这不仅有助于从后端视角深入分析系统瓶颈,还能在遭遇异常流量或大规模攻击时,精准定位到特定接口并进行针对性优化。
项目环境:
- 框架版本:Laravel 5.8及以上
- 缓存组件:Redis 2.6.0及以上
当前项目主要采用GraphQL接口架构,使用的包为php-lighthouse-graphql。因此,核心需求在于准确统计GraphQL接口的请求次数,以支撑后续的数据分析工作。
实现GraphQL Record Middleware
首先,需要创建一个中间件,用于后续记录接口的请求频率。可以利用Artisan命令行工具快速生成中间件文件:
php artisan make:middleware GraphQLRecord
<?php
namespace App\Http\Middleware;
use Closure;
class GraphQLRecord
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
return $next($request);
}
}
创建完成后,需将该中间件添加到配置中。可以在app/config/lighthouse.php的middleware配置项中添加,或者将其注册到项目的app/Http/Kernel.php中,并设置为全局中间件以确保生效。
'middleware' => [
\App\Http\Middleware\GraphQLRecord::class,
\Nuwave\Lighthouse\Support\Http\Middleware\AcceptJson::class,
],
获取 GraphQL Operation Name
public function handle($request, Closure $next)
{
$opName = $request->get('operationName');
return $next($request);
}
在中间件中,首先需要提取GraphQL请求中的Operation Name(操作名称)。获取到这一唯一标识后,即可基于Redis构建接口计数器,开始对请求进行追踪。
添加接口计数器
为了实现多维度的频率统计,需要定义多个时间窗口,例如5秒、60秒、半小时、1小时、5小时以及24小时等。这些时间阈值可以存储在一个数组中,具体数值可根据实际业务需求进行调整。
const PRECISION = [5, 60, 1800, 3600, 86400];
接着,编写核心的计数逻辑。每次请求到达时,计算当前时间所属的时间片,并将计数结果存入Redis的ZSET(有序集合)中。使用ZSET便于后续进行范围查询和数据聚合操作。
/**
* 更新请求计数器
*
* @param string $opName
* @param integer $count
* @return void
*/
public function updateRequestCounter(string $opName, $count = 1)
{
$now = microtime(true);
$redis = self::getRedisConn();
if ($redis) {
$pipe = $redis->pipeline();
foreach (self::PRECISION as $prec) {
//计算时间片
$pnow = intval($now / $prec) * $prec;
//生成一个hash key标识
$hash = "request:counter:{$prec}:$opName";
//增长接口请求数
$pipe->hincrby($hash, $pnow, 1);
// 添加到集合中,方便后续数据查询
$pipe->zadd('request:counter', [$hash => 0]);
}
$pipe->execute();
}
}
/**
* 获取Redis连接
*
* @return object
*/
public static function getRedisConn()
{
$redis = Redis::connection('cache');
try {
$redis->ping();
} catch (Exception $ex) {
$redis = null;
//丢给sentry报告
app('sentry')->captureException($ex);
}
return $redis;
}
完成代码部署后,发起一次接口请求,并使用Medis客户端连接Redis查看数据,确认计数器是否正常工作。


查询、分析数据
当数据记录完善后,可以通过opName(操作名称)和prec(精度/时间窗口)两个属性进行灵活查询。例如,若要查询tag接口在过去24小时内的访问数据,只需传入对应的参数即可。
/**
* 获取接口访问计数
*
* @param string $opName
* @param integer $prec
* @return array
*/
public static function getRequestCounter(string $opName, int $prec)
{
$data = [];
$redis = self::getRedisConn();
if ($redis) {
$hash = "request:counter:{$prec}:$opName";
$hashData = $redis->hgetall($hash);
foreach ($hashData as $k => $v) {
$date = date("Y/m/d", $k);
$data[] = ['timestamp' => $k, 'value' => $v, 'date' => $date];
}
}
return $data;
}
获取 tag 接口 24小时的访问统计
$data = $this->getRequestCounter('tagQuery', '86400');
清除数据
随着数据统计的积累,系统中会存在大量过期且不再必要的数据。为了保持Redis内存的高效利用,建议通过定时任务定期清理这些数据。具体的清理逻辑实现如下:
/**
* 清理请求计数
*
* @param integer $clearDay
* @return void
*/
public function clearRequestCounter($clearDay = 7)
{
$index = 0;
$startTime = microtime(true);
$redis = self::getRedisConn();
if ($redis) {
//可以清理的情况下
while ($index < $redis->zcard('request:counter')) {
$hash = $redis->zrange('request:counter', $index, $index);
$index++;
//当前hash存在
if ($hash) {
$hash = $hash[0];
//计算删除截止时间
$cutoff = intval(microtime(true) - ($clearDay * 24 * 60 * 60));
//优先删除时间较远的数据
$samples = array_map('intval', $redis->hkeys($hash));
sort($samples);
//需要删除的数据
$removes = array_filter($samples, function ($item) use (&$cutoff) {
return $item <= $cutoff;
});
if (count($removes)) {
$redis->hdel($hash, ...$removes);
//如果整个数据都过期了的话,就清除掉统计的数据
if (count($removes) == count($samples)) {
$trans = $redis->transaction(['cas' => true]);
try {
$trans->watch($hash);
if (!$trans->hlen($hash)) {
$trans->multi();
$trans->zrem('request:counter', $hash);
$trans->execute();
$index--;
} else {
$trans->unwatch();
}
} catch (\Exception $ex) {
dump($ex);
}
}
}
}
}
dump('清理完成');
}
}
清理一个30天前的数据:
$this->clearRequestCounter(30);
整合代码
为了提升代码的可维护性和复用性,我们将所有与接口统计相关的逻辑封装到一个独立的类中,并提供静态方法供外部调用。这种设计不仅符合单一职责原则,也方便将统计功能集成到其他不同的模块中。
<?php
namespace App\Helpers;
use Illuminate\Support\Facades\Redis;
class RequestCounter
{
const PRECISION = [5, 60, 1800, 3600, 86400];
const REQUEST_COUNTER_CACHE_KEY = 'request:counter';
/**
* 更新请求计数器
*
* @param string $opName
* @param integer $count
* @return void
*/
public static function updateRequestCounter(string $opName, $count = 1)
{
$now = microtime(true);
$redis = self::getRedisConn();
if ($redis) {
$pipe = $redis->pipeline();
foreach (self::PRECISION as $prec) {
//计算时间片
$pnow = intval($now / $prec) * $prec;
//生成一个hash key标识
$hash = self::counterCacheKey($opName, $prec);
//增长接口请求数
$pipe->hincrby($hash, $pnow, 1);
// 添加到集合中,方便后续数据查询
$pipe->zadd(self::REQUEST_COUNTER_CACHE_KEY, [$hash => 0]);
}
$pipe->execute();
}
}
/**
* 获取Redis连接
*
* @return object
*/
public static function getRedisConn()
{
$redis = Redis::connection('cache');
try {
$redis->ping();
} catch (Exception $ex) {
$redis = null;
//丢给sentry报告
app('sentry')->captureException($ex);
}
return $redis;
}
/**
* 获取接口访问计数
*
* @param string $opName
* @param integer $prec
* @return array
*/
public static function getRequestCounter(string $opName, int $prec)
{
$data = [];
$redis = self::getRedisConn();
if ($redis) {
$hash = self::counterCacheKey($opName, $prec);
$hashData = $redis->hgetall($hash);
foreach ($hashData as $k => $v) {
$date = date("Y/m/d", $k);
$data[] = ['timestamp' => $k, 'value' => $v, 'date' => $date];
}
}
return $data;
}
/**
* 清理请求计数
*
* @param integer $clearDay
* @return void
*/
public static function clearRequestCounter($clearDay = 7)
{
$index = 0;
$startTime = microtime(true);
$redis = self::getRedisConn();
if ($redis) {
//可以清理的情况下
while ($index < $redis->zcard(self::REQUEST_COUNTER_CACHE_KEY)) {
$hash = $redis->zrange(self::REQUEST_COUNTER_CACHE_KEY, $index, $index);
$index++;
//当前hash存在
if ($hash) {
$hash = $hash[0];
//计算删除截止时间
$cutoff = intval(microtime(true) - ($clearDay * 24 * 60 * 60));
//优先删除时间较远的数据
$samples = array_map('intval', $redis->hkeys($hash));
sort($samples);
//需要删除的数据
$removes = array_filter($samples, function ($item) use (&$cutoff) {
return $item <= $cutoff;
});
if (count($removes)) {
$redis->hdel($hash, ...$removes);
//如果整个数据都过期了的话,就清除掉统计的数据
if (count($removes) == count($samples)) {
$trans = $redis->transaction(['cas' => true]);
try {
$trans->watch($hash);
if (!$trans->hlen($hash)) {
$trans->multi();
$trans->zrem(self::REQUEST_COUNTER_CACHE_KEY, $hash);
$trans->execute();
$index--;
} else {
$trans->unwatch();
}
} catch (\Exception $ex) {
dump($ex);
}
}
}
}
}
dump('清理完成');
}
}
public static function counterCacheKey($opName, $prec)
{
$key = "request:counter:{$prec}:$opName";
return $key;
}
}
在Middleware中使用.
<?php
namespace App\Http\Middleware;
use App\Helpers\RequestCounter;
use Closure;
class GraphQLRecord
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$opName = $request->get('operationName');
if (!empty($opName)) {
RequestCounter::updateRequestCounter($opName);
}
return $next($request);
}
}
结尾
上述代码实现了基于GraphQL的请求频率记录功能。实际上,该方案并不局限于GraphQL接口,同样适用于Restful API或其他模块的计数场景。只要请求中存在唯一的operation name标识,即可套用此逻辑进行统计。
到此这篇关于Laravel中GraphQL接口请求频率的文章就介绍到这了,更多相关Laravel中GraphQL接口请求频率内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!