throttle.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | 节流设置
  4. // +----------------------------------------------------------------------
  5. use think\middleware\Throttle;
  6. use think\middleware\throttle\CounterFixed;
  7. use think\Request;
  8. use think\Response;
  9. return [
  10. // 缓存键前缀,防止键值与其他应用冲突
  11. 'prefix' => 'throttle_',
  12. // 缓存的键,true 表示使用来源ip
  13. 'key' => true,
  14. // 要被限制的请求类型, eg: GET POST PUT DELETE HEAD 等
  15. 'visit_method' => ['GET', 'HEAD'],
  16. // 设置访问频率,例如 '10/m' 指的是允许每分钟请求10次;'10/60'指允许每60秒请求10次。值 null 表示不限制, eg: null 10/m 20/h 300/d 200/300
  17. 'visit_rate' => '120/m',
  18. /*
  19. * 设置节流算法,组件提供了四种算法:
  20. * - CounterFixed :计数固定窗口
  21. * - CounterSlider: 滑动窗口
  22. * - TokenBucket : 令牌桶算法
  23. * - LeakyBucket : 漏桶限流算法
  24. */
  25. 'driver_name' => CounterFixed::class,
  26. // 响应体中设置速率限制的头部信息,含义见:https://docs.github.com/en/rest/overview/resources-in-the-rest-api#rate-limiting
  27. 'visit_enable_show_rate_limit' => true,
  28. // 访问受限时返回的响应
  29. 'visit_fail_response' => function (Throttle $throttle, Request $request, int $wait_seconds) {
  30. return Response::create([
  31. 'code' => 0,
  32. 'msg' => 'Please do not request frequently. Try again in ' . $wait_seconds . ' seconds.',
  33. ], 'json')->header([
  34. 'Access-Control-Allow-Credentials' => 'true',
  35. 'Access-Control-Max-Age' => 0,
  36. 'Access-Control-Allow-Methods' => '*',
  37. 'Access-Control-Allow-Headers' => '*',
  38. 'Access-Control-Allow-Origin' => '*',
  39. ]);
  40. },
  41. ];