Php Laravel 5.2缓存增量问题与过期时间

Php Laravel 5.2缓存增量问题与过期时间,php,caching,laravel-5.2,Php,Caching,Laravel 5.2,我在第一个http请求中向缓存添加一个密钥,缓存时间为x分钟,然后在下一个请求中继续递增 我面临的问题是,在递增时,缓存过期时间也会被重置,我需要保留过期时间。我还以秒为单位显示过期时间 下面是我的代码: $key = $input['device_id']; if(! $attempts = Cache::get($key)) { Cache::put($key, 1, Carbon::now()->addMinutes(5)); } else { Cache::increme

我在第一个http请求中向缓存添加一个密钥,缓存时间为x分钟,然后在下一个请求中继续递增

我面临的问题是,在递增时,缓存过期时间也会被重置,我需要保留过期时间。我还以秒为单位显示过期时间

下面是我的代码:

$key = $input['device_id'];
if(! $attempts = Cache::get($key))
{
   Cache::put($key, 1, Carbon::now()->addMinutes(5));
}
else
{
  Cache::increment($key);
}

您可以扩展内置中间件
ThrottlesRequests
,并将其附加到登录路径:

 class MyThrottleRequests extends \Illuminate\Routing\Middleware\ThrottlesRequests {

      protected function resolveRequestSignature($input) {
              return $input->device_id; //I think this is what you mean to use right?
      }

 }
然后,您可以在
Kernel.php

  protected $routeMiddleware = [
       // Existing ones
       'throttleDeviceId' => MyThrottleRequests::class
  ]; 
然后,您可以在所需路线上使用它,如下所示:

  \Route::any("/route/to/throttle",/* Route definition */)->middleware("throttle:<max requests>,<within time>");
\Route::any(“/Route/to/throttle”,/*路由定义*/)->中间件(“throttle:,”;

为什么在Laravel附带开箱即用功能时会这样做?默认的laravel安装中已经定义了一个
throttle
中间件。我的throttling仅基于IP,我正在使用一些其他数据,如设备唯一ID。实际上,此api用于移动应用程序。我的观点是RateLimiter似乎提供了您需要的所有功能。嗯,你知道有哪一个例子是RateLimiter用于自定义唯一密钥而不是IP上的吗?非常感谢!感谢@apokryfos的推荐。这对我有用!