這里寫描述
我做了一個定時任務(wù),用來每天減少用戶的day值。
任務(wù)類:
class DailyTask
{
public function onWorkerStart()
{
new Crontab('0 0 * * *', function () {
$data = Admin::where('day', '>', 0)->select('id')->get()->toArray();
foreach ($data as $item) {
Client::send('reduce-day', $item);
}
Log::info('執(zhí)行每日任務(wù):' . date('Y-m-d H:i:s') . '/數(shù)量:' . count($data));
});
}
}
在config/process.php中添加
'dailyTask' => [
'handler' => \app\process\DailyTask::class
],
對應(yīng)創(chuàng)建了一個消費類
class ReduceDay implements Consumer
{
// 要消費的隊列名
public $queue = 'reduce-day';
// 連接名,對應(yīng) plugin/webman/redis-queue/redis.php 里的連接`
public $connection = 'default';
// 消費
public function consume($data)
{
try {
// 檢查數(shù)據(jù)庫連接是否可用
Db::connection('plugin.admin.mysql')->select('SELECT 1');
} catch (\Exception $e) {
Db::connection('plugin.admin.mysql')->reconnect(); // 重新連接數(shù)據(jù)庫
Log::channel('queue')->info('數(shù)據(jù)庫連接已斷開,正在重連...');
}
Admin::where('id', $data['id'])->decrement('day');
}
public function onConsumeFailure(\Throwable $e, $package)
{
Log::channel('queue')->info('執(zhí)行每日減日期失敗');
Log::channel('queue')->info($e->getMessage());
Log::channel('queue')->info(json_encode($package, true));
}
}
結(jié)果,在實際的每天運行過程中都會報錯:
2006 MySQL server has gone away
我最開始沒有加入:
try {
// 檢查數(shù)據(jù)庫連接是否可用
Db::connection('plugin.admin.mysql')->select('SELECT 1');
} catch (\Exception $e) {
Db::connection('plugin.admin.mysql')->reconnect(); // 重新連接數(shù)據(jù)庫
Log::channel('queue')->info('數(shù)據(jù)庫連接已斷開,正在重連...');
}
這串代碼的時候,有時候他會減少掉,但有時候不會。
加入之后,雖然會每天減少了,但是還是依然會有報錯。
這里寫具體的系統(tǒng)環(huán)境相關(guān)信息
Ubuntu 24.04
MySQL 5.7.44
Nginx 1.24.0
PHP-8.3
webman/database 升級到最新版
我已經(jīng)更新到最新版了,還是會時不時出現(xiàn)這個情況。我沒有使用協(xié)程。然后,我的數(shù)據(jù)庫配置如下:
'default' => 'mysql',
// 各種數(shù)據(jù)庫配置
'connections' => [
'mysql' => [
'driver' => 'mysql',
'host' => '127.0.0.1',
'port' => 3306,
'database' => '',
'username' => '',
'password' => '',
'unix_socket' => '',
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_general_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
'options' => [
PDO::ATTR_EMULATE_PREPARES => false, // 當(dāng)使用swoole或swow作為驅(qū)動時是必須的
],
'pool' => [ // 連接池配置
'max_connections' => 500, // 最大連接數(shù)
'min_connections' => 1, // 最小連接數(shù)
'wait_timeout' => 3, // 從連接池獲取連接等待的最大時間,超時后會拋出異常。僅在協(xié)程環(huán)境有效
'idle_timeout' => 60, // 連接池中連接最大空閑時間,超時后會關(guān)閉回收,直到連接數(shù)為min_connections
'heartbeat_interval' => 50, // 連接池心跳檢測時間,單位秒,建議小于60秒
]
],
],