ImportWhiteWordsCommand.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. <?php
  2. namespace App\Command;
  3. use App\Model\BlackWord;
  4. use App\Model\WhiteWord;
  5. use Hyperf\Command\Annotation\Command;
  6. use Hyperf\Command\Command as HyperfCommand;
  7. use Hyperf\Di\Annotation\Inject;
  8. use Hyperf\Redis\Redis;
  9. // 假设这是一个命令类,用于执行导入违禁词的操作
  10. // 可以通过命令行运行该命令:php bin/hyperf.php import:whitewords
  11. #[Command]
  12. class ImportWhiteWordsCommand extends HyperfCommand
  13. {
  14. public function __construct()
  15. {
  16. parent::__construct('import:whitewords');
  17. }
  18. #[Inject]
  19. protected Redis $redis;
  20. public function handle()
  21. {
  22. // 假设这是从数据库或文件中获取的 30 万条违禁词数组
  23. // 这里只是示例,实际应用中需要从相应数据源读取
  24. $badWords = WhiteWord::pluck('name')->toArray();
  25. // 使用集合(Set)类型存储违禁词,键名为 'bad_words_set'
  26. $redisKey = 'white_word';
  27. $result = $this->redis->del($redisKey);
  28. if ($result === 1) {
  29. $this->info('已成功清空 white_word 集合。');
  30. } else {
  31. $this->error('清空 white_word 集合失败。');
  32. }
  33. // 开始事务,确保一次性导入所有违禁词
  34. $this->redis->multi();
  35. foreach ($badWords as $badWord) {
  36. $this->redis->sAdd($redisKey, $badWord);
  37. }
  38. $this->redis->exec();
  39. $this->info('白名单已成功导入到 Redis 中!');
  40. }
  41. }