BlockerMiddleware.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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 crmeb\exceptions\ApiException;
  16. use crmeb\interfaces\MiddlewareInterface;
  17. use crmeb\services\CacheService;
  18. /**
  19. * reids锁
  20. * Class BlockerMiddleware
  21. * @author 等风来
  22. * @email 136327134@qq.com
  23. * @date 2022/11/21
  24. * @package app\http\middleware\api
  25. */
  26. class BlockerMiddleware implements MiddlewareInterface
  27. {
  28. /**
  29. * @param Request $request
  30. * @param \Closure $next
  31. * @author 等风来
  32. * @email 136327134@qq.com
  33. * @date 2022/11/21
  34. */
  35. public function handle(Request $request, \Closure $next)
  36. {
  37. $uid = $request->uid();
  38. $key = md5($request->rule()->getRule() . $uid);
  39. if (!CacheService::setMutex($key)) {
  40. throw new ApiException('请求太过频繁,请稍后再试');
  41. }
  42. $response = $next($request);
  43. $this->after($response, $key);
  44. return $response;
  45. }
  46. /**
  47. * @param $response
  48. * @param $key
  49. * @author 等风来
  50. * @email 136327134@qq.com
  51. * @date 2022/11/22
  52. */
  53. public function after($response, $key)
  54. {
  55. CacheService::delMutex($key);
  56. }
  57. }