123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106 |
- <?php
- /**
- * Created by PhpStorm.
- * User: Bear
- * Date: 2019/11/13
- * Time: 下午2:52
- */
- namespace app\main\service;
- use app\common\library\Redis;
- use app\main\constants\ErrorCodeConstants;
- use think\Config;
- use think\Request;
- /**
- * 访问限制
- * Class VisitLimitService
- * @package app\main\service
- */
- class VisitLimitService extends BaseService
- {
- /**
- * @var VisitLimitService
- */
- protected static $self = NULL;
- public static function instance()
- {
- if (self::$self == NULL) {
- self::$self = new self();
- }
- return self::$self;
- }
- /**
- * @param $limit
- * @param array ...$values
- * @return \app\main\model\object\ReturnObject
- */
- public function visitLimit($limit, ...$values)
- {
- $keys[] = date('i');
- if (Request::instance()->isAjax()) {
- $keys[] = 'AJAX';
- }
- foreach ($values as $item) {
- if ($item) {
- $keys[] = $item;
- }
- }
- $cacheKey = 'VISIT:' . implode(':', $keys);
- LogService::debug($cacheKey);
- $value = Redis::instance()->incrBy($cacheKey, 1);
- Redis::instance()->expire($cacheKey, 60);
- if ($value >= $limit) {
- $this->setCode(ErrorCodeConstants::VISIT_EXCEED)->setMsg('访问过于频繁,请稍后再试');
- if ($value == $limit) {
- LogService::info('EXCEED:limit:' . $cacheKey . ':' . $value . '>=' . $limit);
- } else {
- LogService::info('EXCEED:cache:' . $cacheKey . ':' . $value . '>=' . $limit);
- }
- } else {
- LogService::debug('NORMAL:cache:' . $cacheKey . ':' . $value . '<' . $limit);
- }
- return $this->getReturn();
- }
- /**
- * @param $admin_id
- * @param $uri
- * @return \app\main\model\object\ReturnObject
- */
- public function visitAdminUri($admin_id, $uri)
- {
- $adminUriLimit = Config::get('site.adminurilimit');
- if (!$adminUriLimit) {
- $adminUriLimit = 200;
- }
- return $this->visitLimit($adminUriLimit, $admin_id, $uri);
- }
- /**
- * @param $ip
- * @param $uri
- * @return \app\main\model\object\ReturnObject
- */
- public function visitIpUri($ip, $uri)
- {
- $ipUriLimit = Config::get('site.ipurilimit');
- if (!$ipUriLimit) {
- $ipUriLimit = 200;
- }
- return $this->visitLimit($ipUriLimit, $ip, $uri);
- }
- public function checkMigratedV2()
- {
- return false;
- }
- public function checkMigrated()
- {
- return false;
- }
- }
|