Xboard/app/Jobs/TrafficFetchJob.php

80 lines
2.7 KiB
PHP
Raw Normal View History

2023-11-17 01:44:01 -05:00
<?php
namespace App\Jobs;
use App\Models\User;
use App\Services\MailService;
use App\Services\ServerService;
use App\Services\StatisticalService;
2023-11-17 01:44:01 -05:00
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class TrafficFetchJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $data;
2023-11-17 01:44:01 -05:00
protected $server;
protected $childServer;
2023-11-17 01:44:01 -05:00
protected $protocol;
protected $timestamp;
public $tries = 1;
2023-11-17 01:44:01 -05:00
public $timeout = 10;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct(array $server, array $data, $protocol, int $timestamp, $childServer = null)
2023-11-17 01:44:01 -05:00
{
$this->onQueue('traffic_fetch');
$this->server = $server;
$this->data = $data;
2023-11-17 01:44:01 -05:00
$this->protocol = $protocol;
$this->timestamp = $timestamp;
$this->childServer = $childServer;
2023-11-17 01:44:01 -05:00
}
public function handle(): void
{
if ($this->attempts() === 1) {
$statService = new StatisticalService();
$statService->setStartAt($this->timestamp);
$statService->setUserStats();
$statService->setServerStats();
}
// 获取子节点\
$targetServer = $this->childServer ?? $this->server;
foreach ($this->data as $uid => $v) {
\DB::transaction(function () use ($uid, $v, $targetServer, $statService) {
$u = $v[0];
$d = $v[1];
$user = \DB::table('v2_user')->lockForUpdate()->where('id', $uid)->first();
if (!$user) {
return;
}
if ($this->attempts() === 1) { // 写缓存
$statService->statUser($targetServer['rate'], $uid, $u, $d); //如果存在子节点则使用子节点的倍率
if (!blank($this->childServer)) { //如果存在子节点,则给子节点计算流量
$statService->statServer($this->childServer['id'], $this->protocol, $u, $d);
}
$statService->statServer($this->server['id'], $this->protocol, $u, $d);
}
$newTime = time();
$newU = $user->u + ($v[0] * $targetServer['rate']);
$newD = $user->d + ($v[1] * $targetServer['rate']);
\DB::table('v2_user')
->where('id', $uid)
->update([
't' => $newTime,
'u' => $newU,
'd' => $newD,
]);
}, 3);
}
2023-11-17 01:44:01 -05:00
}
}