VisitLimitService.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: Bear
  5. * Date: 2019/11/13
  6. * Time: 下午2:52
  7. */
  8. namespace app\main\service;
  9. use app\common\library\Redis;
  10. use app\main\constants\ErrorCodeConstants;
  11. use think\Config;
  12. use think\Request;
  13. /**
  14. * 访问限制
  15. * Class VisitLimitService
  16. * @package app\main\service
  17. */
  18. class VisitLimitService extends BaseService
  19. {
  20. /**
  21. * @var VisitLimitService
  22. */
  23. protected static $self = NULL;
  24. public static function instance()
  25. {
  26. if (self::$self == NULL) {
  27. self::$self = new self();
  28. }
  29. return self::$self;
  30. }
  31. /**
  32. * @param $limit
  33. * @param array ...$values
  34. * @return \app\main\model\object\ReturnObject
  35. */
  36. public function visitLimit($limit, ...$values)
  37. {
  38. $keys[] = date('i');
  39. if (Request::instance()->isAjax()) {
  40. $keys[] = 'AJAX';
  41. }
  42. foreach ($values as $item) {
  43. if ($item) {
  44. $keys[] = $item;
  45. }
  46. }
  47. $cacheKey = 'VISIT:' . implode(':', $keys);
  48. LogService::debug($cacheKey);
  49. $value = Redis::instance()->incrBy($cacheKey, 1);
  50. Redis::instance()->expire($cacheKey, 60);
  51. if ($value >= $limit) {
  52. $this->setCode(ErrorCodeConstants::VISIT_EXCEED)->setMsg('访问过于频繁,请稍后再试');
  53. if ($value == $limit) {
  54. LogService::info('EXCEED:limit:' . $cacheKey . ':' . $value . '>=' . $limit);
  55. } else {
  56. LogService::info('EXCEED:cache:' . $cacheKey . ':' . $value . '>=' . $limit);
  57. }
  58. } else {
  59. LogService::debug('NORMAL:cache:' . $cacheKey . ':' . $value . '<' . $limit);
  60. }
  61. return $this->getReturn();
  62. }
  63. /**
  64. * @param $admin_id
  65. * @param $uri
  66. * @return \app\main\model\object\ReturnObject
  67. */
  68. public function visitAdminUri($admin_id, $uri)
  69. {
  70. $adminUriLimit = Config::get('site.adminurilimit');
  71. if (!$adminUriLimit) {
  72. $adminUriLimit = 200;
  73. }
  74. return $this->visitLimit($adminUriLimit, $admin_id, $uri);
  75. }
  76. /**
  77. * @param $ip
  78. * @param $uri
  79. * @return \app\main\model\object\ReturnObject
  80. */
  81. public function visitIpUri($ip, $uri)
  82. {
  83. $ipUriLimit = Config::get('site.ipurilimit');
  84. if (!$ipUriLimit) {
  85. $ipUriLimit = 200;
  86. }
  87. return $this->visitLimit($ipUriLimit, $ip, $uri);
  88. }
  89. public function checkMigratedV2()
  90. {
  91. return false;
  92. }
  93. public function checkMigrated()
  94. {
  95. return false;
  96. }
  97. }