這里寫描述
我做了一個(gè)定時(shí)任務(wù),用來(lái)每天減少用戶的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
],
對(duì)應(yīng)創(chuàng)建了一個(gè)消費(fèi)類
class ReduceDay implements Consumer
{
// 要消費(fèi)的隊(duì)列名
public $queue = 'reduce-day';
// 連接名,對(duì)應(yīng) plugin/webman/redis-queue/redis.php 里的連接`
public $connection = 'default';
// 消費(fèi)
public function consume($data)
{
try {
// 檢查數(shù)據(jù)庫(kù)連接是否可用
Db::connection('plugin.admin.mysql')->select('SELECT 1');
} catch (\Exception $e) {
Db::connection('plugin.admin.mysql')->reconnect(); // 重新連接數(shù)據(jù)庫(kù)
Log::channel('queue')->info('數(shù)據(jù)庫(kù)連接已斷開(kāi),正在重連...');
}
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é)果,在實(shí)際的每天運(yùn)行過(guò)程中都會(huì)報(bào)錯(cuò):
2006 MySQL server has gone away
我最開(kāi)始沒(méi)有加入:
try {
// 檢查數(shù)據(jù)庫(kù)連接是否可用
Db::connection('plugin.admin.mysql')->select('SELECT 1');
} catch (\Exception $e) {
Db::connection('plugin.admin.mysql')->reconnect(); // 重新連接數(shù)據(jù)庫(kù)
Log::channel('queue')->info('數(shù)據(jù)庫(kù)連接已斷開(kāi),正在重連...');
}
這串代碼的時(shí)候,有時(shí)候他會(huì)減少掉,但有時(shí)候不會(huì)。
加入之后,雖然會(huì)每天減少了,但是還是依然會(huì)有報(bào)錯(cuò)。
這里寫具體的系統(tǒng)環(huán)境相關(guān)信息
Ubuntu 24.04
MySQL 5.7.44
Nginx 1.24.0
PHP-8.3
webman/database 升級(jí)到最新版
我已經(jīng)更新到最新版了,還是會(huì)時(shí)不時(shí)出現(xiàn)這個(gè)情況。我沒(méi)有使用協(xié)程。然后,我的數(shù)據(jù)庫(kù)配置如下:
'default' => 'mysql',
// 各種數(shù)據(jù)庫(kù)配置
'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ū)動(dòng)時(shí)是必須的
],
'pool' => [ // 連接池配置
'max_connections' => 500, // 最大連接數(shù)
'min_connections' => 1, // 最小連接數(shù)
'wait_timeout' => 3, // 從連接池獲取連接等待的最大時(shí)間,超時(shí)后會(huì)拋出異常。僅在協(xié)程環(huán)境有效
'idle_timeout' => 60, // 連接池中連接最大空閑時(shí)間,超時(shí)后會(huì)關(guān)閉回收,直到連接數(shù)為min_connections
'heartbeat_interval' => 50, // 連接池心跳檢測(cè)時(shí)間,單位秒,建議小于60秒
]
],
],