ImportBadWordsCommand.php 1.5 KB

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