SsdbIgnoreKeyFormat.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: lts
  5. * Date: 13/8/18
  6. * Time: 下午3:34
  7. */
  8. namespace app\admin\command;
  9. use think\console\Command;
  10. use think\console\Input;
  11. use think\console\input\Option;
  12. use think\console\Output;
  13. use think\Request;
  14. use app\common\library\Ssdb;
  15. use app\common\constants\User;
  16. use think\Log;
  17. class SsdbIgnoreKeyFormat extends Command
  18. {
  19. /**
  20. * @var Output
  21. */
  22. private $_output;
  23. protected function configure()
  24. {
  25. $this->setName('SsdbIgnoreKeyFormat')
  26. ->setDescription('将原有白名单ignore转为IG,从分组0拆分一个大hash,到分组1为多个小hash');
  27. }
  28. protected function execute(Input $input, Output $output)
  29. {
  30. Request::instance()->module('admin'); //cli模式下无法获取到当前的项目模块,手动指定一下
  31. $this->_output = $output;
  32. try {
  33. $msg = '白名单ignore转为IG--begin';
  34. $this->logInfo($msg);
  35. $ssdb = Ssdb::instance();
  36. $oldKey = 'ignore';
  37. $batchIndex = 0;
  38. while (true) {
  39. $batchIndex++;
  40. $ipList = $ssdb->hkeys($oldKey, '', '', 5000);
  41. $this->logInfo(sprintf('批次:%s,key数量:%s。', $batchIndex, count($ipList)));
  42. if (empty($ipList)) {
  43. $this->logInfo('当前批次key数量为0,退出程序');
  44. break;
  45. }
  46. foreach ($ipList as $ip) {
  47. $msg = sprintf('%s IgnoreIp:%s', date('Y-m-d H:i:s'), $ip);
  48. $this->logInfo($msg);
  49. $ignoreIpKey = User::getIgnoreIpKey($ip);
  50. if (!$ssdb->hexists($ignoreIpKey, $ip)) {
  51. $ssdb->hset($ignoreIpKey, $ip, '');
  52. }
  53. $ssdb->hdel($oldKey, $ip);
  54. }
  55. }
  56. $msg = '白名单ignore转为IG--end';
  57. $this->logInfo($msg);
  58. } catch (\Exception $e) {
  59. $errMsg = date('Y-m-d H:i:s') . $e->getMessage();
  60. $this->logError($errMsg);
  61. }
  62. }
  63. /**
  64. * @param $msg
  65. */
  66. private function logInfo($msg)
  67. {
  68. Log::info($msg);
  69. $this->_output->writeln($msg);
  70. }
  71. /**
  72. * @param $msg
  73. */
  74. private function logError($msg)
  75. {
  76. Log::error($msg);
  77. $this->_output->writeln($msg);
  78. }
  79. }