BlockerMiddleware.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. /**
  3. * +----------------------------------------------------------------------
  4. * | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  5. * +----------------------------------------------------------------------
  6. * | Copyright (c) 2016~2023 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\api\middleware;
  14. use app\Request;
  15. use crmeb\exceptions\ApiException;
  16. use crmeb\interfaces\MiddlewareInterface;
  17. use crmeb\services\CacheService;
  18. use think\facade\Config;
  19. /**
  20. * Redis锁
  21. * Class BlockerMiddleware
  22. * @author 等风来
  23. * @email 136327134@qq.com
  24. * @date 2023/2/8
  25. * @package app\api\middleware
  26. */
  27. class BlockerMiddleware implements MiddlewareInterface
  28. {
  29. /**
  30. * @param Request $request
  31. * @param \Closure $next
  32. * @author 等风来
  33. * @email 136327134@qq.com
  34. * @date 2022/11/21
  35. */
  36. public function handle(Request $request, \Closure $next)
  37. {
  38. if (Config::get('cache.default') == 'file') {
  39. return $next($request);
  40. }
  41. $uid = $request->uid();
  42. $key = md5($request->rule()->getRule() . $uid);
  43. if (!CacheService::setMutex($key)) {
  44. throw new ApiException('请求太过频繁,请稍后再试');
  45. }
  46. $response = $next($request);
  47. $this->after($response, $key);
  48. return $response;
  49. }
  50. /**
  51. * @param $response
  52. * @param $key
  53. * @author 等风来
  54. * @email 136327134@qq.com
  55. * @date 2022/11/22
  56. */
  57. public function after($response, $key)
  58. {
  59. CacheService::delMutex($key);
  60. }
  61. }