How to use retryHandler #19429
Unanswered
EtienneBruines
asked this question in
Q&A
Replies: 2 comments 7 replies
-
Deadlock is not server "gone away", is "busy", PDO tells you what to do: try restarting transaction. Also, you can enable |
Beta Was this translation helpful? Give feedback.
4 replies
-
I ended up creating my own <?php
namespace common\components;
use yii\db\Command;
/**
* Retries commands if they fail with MySQL gone away or retrying transaction.
*/
class RetryingCommand extends Command
{
public function init()
{
parent::init();
$this->setRetryHandler(static function (\yii\db\Exception $e, $attempt) {
if (str_contains($e->getMessage(), 'MySQL server has gone away')) {
// The MySQL connection got dropped / disconnected, so let's reconnect
\Yii::$app->getDb()->close();
\Yii::$app->getDb()->open();
return true; // retry the SQL command
}
if (str_contains($e->getMessage(), 'try restarting transaction')) {
// Deadlock issues with Galera cluster - two commands updating the same data in parallel
return true; // retry the SQL command
}
return false; // do not retry, but throw error
});
}
} And then specifying it in the config: <?php
return [
'components' => [
'db' => [
'class' => \yii\db\Connection::class,
'dsn' => 'mysql:host=mysql;port=3306;dbname=db1',
'username' => 'root',
'password' => 'super-duper-secure-password',
'charset' => 'utf8',
'attributes' => [
PDO::ATTR_PERSISTENT => true,
],
'commandClass' => \common\components\RetryingCommand::class,
],
] ,
]; |
Beta Was this translation helpful? Give feedback.
3 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Sometimes, connections to MySQL servers aren't the way you want it to be:
MySQL server has gone away
SQLSTATE[40001]: Serialization failure: 1213 Deadlock found when trying to get lock; try restarting transaction
Since this can happen almost anywhere, I thought I'd see what Yii2 allows me to configure. Stumbled upon the
setRetryHandler
method, which allows me to indicate whether to retry the pdo command. Great!My initial thoughts were this:
And even though this configures the
$config
variable withinYii::$app->db->createCommand
, it does not set the_retryHandler
for the resulting$command = Yii::createObject($config)
How does one use this
retryHandler
? I've seen no documentation and #15924 (comment) doesn't seem practical to use, since I'd have to do this for every use ofcreateCommand
.Beta Was this translation helpful? Give feedback.
All reactions