RebuildRelationCacheCommand.php 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. <?php
  2. namespace App\Module\Team\Commands;
  3. use App\Module\Team\Logics\RelationCacheLogic;
  4. use App\Module\Team\Models\TeamUserReferral;
  5. use Illuminate\Console\Command;
  6. /**
  7. * 重建关系缓存命令
  8. *
  9. * 用于重建用户关系缓存,确保缓存数据的准确性。
  10. */
  11. class RebuildRelationCacheCommand extends Command
  12. {
  13. /**
  14. * 命令名称
  15. *
  16. * @var string
  17. */
  18. protected $signature = 'team:rebuild-relation-cache {--user-id= : 指定用户ID} {--debug-info : 显示详细信息}';
  19. /**
  20. * 命令描述
  21. *
  22. * @var string
  23. */
  24. protected $description = '重建用户关系缓存';
  25. /**
  26. * 关系缓存逻辑类
  27. *
  28. * @var RelationCacheLogic
  29. */
  30. protected $relationCacheLogic;
  31. /**
  32. * 创建命令实例
  33. *
  34. * @param RelationCacheLogic $relationCacheLogic 关系缓存逻辑类
  35. * @return void
  36. */
  37. public function __construct(RelationCacheLogic $relationCacheLogic)
  38. {
  39. parent::__construct();
  40. $this->relationCacheLogic = $relationCacheLogic;
  41. }
  42. /**
  43. * 执行命令
  44. *
  45. * @return int
  46. */
  47. public function handle()
  48. {
  49. $this->info('开始重建关系缓存...');
  50. $userId = $this->option('user-id');
  51. $showDebugInfo = $this->option('debug-info');
  52. try {
  53. if ($userId) {
  54. // 重建指定用户的关系缓存
  55. $this->relationCacheLogic->rebuildUserRelationCache($userId);
  56. if ($showDebugInfo) {
  57. $this->info("用户 {$userId} 的关系缓存重建完成");
  58. } else {
  59. $this->info("重建完成");
  60. }
  61. } else {
  62. // 重建所有用户的关系缓存
  63. $this->relationCacheLogic->clearAllRelationCache();
  64. $users = TeamUserReferral::all();
  65. $total = $users->count();
  66. $current = 0;
  67. if ($showDebugInfo) {
  68. $this->info("共有 {$total} 个用户需要重建关系缓存");
  69. $bar = $this->output->createProgressBar($total);
  70. $bar->start();
  71. }
  72. foreach ($users as $user) {
  73. $this->relationCacheLogic->buildUserRelationCache($user->user_id);
  74. $current++;
  75. if ($showDebugInfo) {
  76. $bar->advance();
  77. }
  78. }
  79. if ($showDebugInfo) {
  80. $bar->finish();
  81. $this->newLine();
  82. $this->info("所有用户的关系缓存重建完成");
  83. } else {
  84. $this->info("重建完成");
  85. }
  86. }
  87. return 0;
  88. } catch (\Exception $e) {
  89. $this->error("重建关系缓存失败: " . $e->getMessage());
  90. if ($showDebugInfo) {
  91. $this->error($e->getTraceAsString());
  92. }
  93. return 1;
  94. }
  95. }
  96. }