TrafficShaperBehavior.php 772 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. <?php
  2. namespace common\behaviors;
  3. use yii\base\Behavior;
  4. use yii\web\Controller;
  5. use yii\web\TooManyRequestsHttpException;
  6. use common\components\TrafficShaper;
  7. /**
  8. * 令牌桶 - 限流行为
  9. *
  10. * Class TrafficShaperBehavior
  11. * @package common\behaviors
  12. * @author qimall
  13. */
  14. class TrafficShaperBehavior extends Behavior
  15. {
  16. /**
  17. * @return array
  18. */
  19. public function events()
  20. {
  21. return [Controller::EVENT_BEFORE_ACTION => 'beforeAction'];
  22. }
  23. /**
  24. * @param $event
  25. * @throws TooManyRequestsHttpException
  26. */
  27. public function beforeAction($event)
  28. {
  29. $trafficShaper = new TrafficShaper();
  30. if (!$trafficShaper->get()) {
  31. throw new TooManyRequestsHttpException('请求过快');
  32. }
  33. }
  34. }