BlockerMiddleware.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. /**
  3. * +----------------------------------------------------------------------
  4. * | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  5. * +----------------------------------------------------------------------
  6. * | Copyright (c) 2016~2022 https://www.crmeb.com All rights reserved.
  7. * +----------------------------------------------------------------------
  8. * | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  9. * +----------------------------------------------------------------------
  10. * | Author: CRMEB Team <admin@crmeb.com>
  11. * +----------------------------------------------------------------------
  12. */
  13. namespace app\http\middleware\api;
  14. use app\Request;
  15. use Closure;
  16. use qiniu\exceptions\ApiException;
  17. use qiniu\interfaces\MiddlewareInterface;
  18. use qiniu\services\CacheService;
  19. /**
  20. * reids锁
  21. * Class BlockerMiddleware
  22. * @author 等风来
  23. * @email 136327134@qq.com
  24. * @date 2022/11/21
  25. * @package app\http\middleware\api
  26. */
  27. class BlockerMiddleware implements MiddlewareInterface
  28. {
  29. /**
  30. * @param Request $request
  31. * @param Closure $next
  32. * @return mixed
  33. * @author 等风来
  34. * @email 136327134@qq.com
  35. * @date 2022/11/21
  36. */
  37. public function handle(Request $request, Closure $next)
  38. {
  39. $uid = $request->uid();
  40. $key = md5($request->rule()->getRule() . $uid);
  41. if (!CacheService::setMutex($key)) {
  42. throw new ApiException('请求太过频繁,请稍后再试');
  43. }
  44. $response = $next($request);
  45. $this->after($response, $key);
  46. return $response;
  47. }
  48. /**
  49. * @param $response
  50. * @param $key
  51. * @author 等风来
  52. * @email 136327134@qq.com
  53. * @date 2022/11/22
  54. */
  55. public function after($response, $key)
  56. {
  57. CacheService::delMutex($key);
  58. }
  59. }