StatServerJob.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. namespace App\Jobs;
  3. use App\Models\StatServer;
  4. use Illuminate\Bus\Queueable;
  5. use Illuminate\Contracts\Queue\ShouldQueue;
  6. use Illuminate\Foundation\Bus\Dispatchable;
  7. use Illuminate\Queue\InteractsWithQueue;
  8. use Illuminate\Queue\SerializesModels;
  9. class StatServerJob implements ShouldQueue
  10. {
  11. use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
  12. protected $u;
  13. protected $d;
  14. protected $server;
  15. protected $protocol;
  16. protected $recordType;
  17. public $tries = 3;
  18. public $timeout = 60;
  19. /**
  20. * Create a new job instance.
  21. *
  22. * @return void
  23. */
  24. public function __construct($u, $d, $server, $protocol, $recordType = 'd')
  25. {
  26. $this->onQueue('stat');
  27. $this->u = $u;
  28. $this->d = $d;
  29. $this->server = $server;
  30. $this->protocol = $protocol;
  31. $this->recordType = $recordType;
  32. }
  33. /**
  34. * Execute the job.
  35. *
  36. * @return void
  37. */
  38. public function handle()
  39. {
  40. $recordAt = strtotime(date('Y-m-d'));
  41. if ($this->recordType === 'm') {
  42. //
  43. }
  44. $data = StatServer::where('record_at', $recordAt)
  45. ->where('server_id', $this->server->id)
  46. ->lockForUpdate()
  47. ->first();
  48. if ($data) {
  49. try {
  50. $data->update([
  51. 'u' => $data['u'] + $this->u,
  52. 'd' => $data['d'] + $this->d
  53. ]);
  54. } catch (\Exception $e) {
  55. abort(500, '节点统计数据更新失败');
  56. }
  57. } else {
  58. if (!StatServer::create([
  59. 'server_id' => $this->server->id,
  60. 'server_type' => $this->protocol,
  61. 'u' => $this->u,
  62. 'd' => $this->d,
  63. 'record_type' => $this->recordType,
  64. 'record_at' => $recordAt
  65. ])) {
  66. abort(500, '节点统计数据创建失败');
  67. }
  68. }
  69. }
  70. }