| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 |
- <?php
- namespace common\behaviors;
- use Yii;
- use yii\base\Behavior;
- use yii\web\Controller;
- use yii\redis\Connection;
- use yii\web\TooManyRequestsHttpException;
- use common\helpers\DateHelper;
- /**
- * 限制点击次数
- * 防止重复提交
- * Class CounterBehavior
- * @package common\behaviors
- * @author qimall
- */
- class LimitBehavior extends Behavior
- {
- /**
- * 请求方法
- *
- * @var string
- */
- public $action = "*";
- /**
- * 用户id
- *
- * @var int
- */
- public $userId = 0;
- /**
- * 过期时间,单位:秒
- *
- * @var float|int
- */
- public $second = 2;
- /**
- * key前缀
- * @var string
- */
- public $prefix = 'REQUESTLIMIT:';
- /**
- * @return array
- */
- public function events()
- {
- return [Controller::EVENT_BEFORE_ACTION => 'beforeAction'];
- }
- /**
- * @param $event
- * @throws TooManyRequestsHttpException
- */
- public function beforeAction($event)
- {
- // 只有post方式才可以需要此处理
- if ($this->userId && Yii::$app->request->isPost) {
- /** @var Connection $redis */
- $redis = Yii::$app->redis;
- // 限流: 用户 + 访问方法
- $key = $this->prefix.sprintf('hist_%s_%s', $this->userId, Yii::$app->controller->route);
- $res = $redis->set($key,1,'NX','EX',$this->second);
- if (!$res) throw new TooManyRequestsHttpException('服务器繁忙,路径:'.Yii::$app->controller->route);
- }
- }
- }
|