V2boardCache.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Utils\CacheKey;
  4. use Illuminate\Console\Command;
  5. use App\Models\ServerLog;
  6. use Illuminate\Support\Facades\Cache;
  7. use Illuminate\Support\Facades\DB;
  8. class V2boardCache extends Command
  9. {
  10. /**
  11. * The name and signature of the console command.
  12. *
  13. * @var string
  14. */
  15. protected $signature = 'v2board:cache';
  16. /**
  17. * The console command description.
  18. *
  19. * @var string
  20. */
  21. protected $description = '缓存任务';
  22. /**
  23. * Create a new command instance.
  24. *
  25. * @return void
  26. */
  27. public function __construct()
  28. {
  29. parent::__construct();
  30. }
  31. /**
  32. * Execute the console command.
  33. *
  34. * @return mixed
  35. */
  36. public function handle()
  37. {
  38. $this->cacheServerStat();
  39. }
  40. private function cacheServerStat()
  41. {
  42. $serverLogs = ServerLog::select(
  43. 'server_id',
  44. DB::raw("sum(u) as u"),
  45. DB::raw("sum(d) as d"),
  46. DB::raw("count(*) as online")
  47. )
  48. ->where('updated_at', '>=', time() - 3600)
  49. ->groupBy('server_id')
  50. ->get();
  51. foreach ($serverLogs as $serverLog) {
  52. $data = [
  53. 'server_id' => $serverLog->server_id,
  54. 'u' => $serverLog->u,
  55. 'd' => $serverLog->d,
  56. 'online' => $serverLog->online
  57. ];
  58. Cache::put(CacheKey::get('SERVER_STAT', $serverLog->server_id), json_encode($data), 3600);
  59. }
  60. }
  61. }