TrafficShaperBehavior.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. namespace common\behaviors;
  3. use Yii;
  4. use yii\base\Behavior;
  5. use yii\helpers\Json;
  6. use yii\web\Controller;
  7. use yii\web\TooManyRequestsHttpException;
  8. use common\components\TrafficShaper;
  9. use common\helpers\Auth;
  10. /**
  11. * 令牌桶 - 限流行为
  12. *
  13. * Class TrafficShaperBehavior
  14. * @package common\behaviors
  15. * @author jianyan74 <751393839@qq.com>
  16. */
  17. class TrafficShaperBehavior extends Behavior
  18. {
  19. /**
  20. * @var bool whether to include rate limit headers in the response
  21. */
  22. public $enable = true;
  23. /**
  24. * @return array
  25. */
  26. public function events()
  27. {
  28. return [Controller::EVENT_BEFORE_ACTION => 'beforeAction'];
  29. }
  30. /**
  31. * @param $event
  32. * @throws TooManyRequestsHttpException
  33. */
  34. public function beforeAction($event)
  35. {
  36. if ($this->enable == false) {
  37. return;
  38. }
  39. $config = Yii::$app->services->config->backendConfigAll();
  40. $isOpen = $config['current_limiting_is_open'] ?? false;
  41. if ($isOpen == false) {
  42. return;
  43. }
  44. $routes = $config['current_limiting_route'] ?? [];
  45. $whiteList = $config['current_limiting_white_list'] ?? [];
  46. !is_array($routes) && $routes = Json::decode($routes);
  47. !is_array($whiteList) && $whiteList = Json::decode($whiteList);
  48. $whiteListRoutes = $whiteList['route'] ?? [];
  49. $url = explode('?', Yii::$app->request->getUrl());
  50. foreach ($routes as $route) {
  51. if ($url[0] == $route['route']) {
  52. $trafficShaper = new TrafficShaper($route['num'], $route['route']);
  53. if (!$trafficShaper->get()) {
  54. // 是否在白名单内
  55. if (!empty($whiteListRoutes) && !in_array($url[0], $whiteListRoutes)) {
  56. throw new TooManyRequestsHttpException('访问太火爆,请稍候');
  57. }
  58. }
  59. }
  60. if ($route['route'] == '*') {
  61. $trafficShaper = new TrafficShaper($route['num'], $route['route']);
  62. if (!$trafficShaper->get()) {
  63. // 是否在白名单内
  64. if (!empty($whiteListRoutes) && !in_array($url[0], $whiteListRoutes)) {
  65. throw new TooManyRequestsHttpException('访问太火爆,请稍候');
  66. }
  67. }
  68. }
  69. }
  70. }
  71. }
粤ICP备19079148号