Go Mysql Deadlock检测


原文链接: Go Mysql Deadlock检测

golang中实现 Mysql 死锁检测

// IsDeadlock checks if error is deadlock
func IsDeadlock(err error) bool {
	knownDatabaseErrorMessages := []string{
		"Deadlock found when trying to get lock; try restarting transaction", /* MySQL / MariaDB */
		"database is locked",                                                 /* SQLite */
	}

	for _, msg := range knownDatabaseErrorMessages {
		if strings.Contains(err.Error(), msg) {
			return true
		}
	}

	return false
}

func GetRetryInterval(retryInterval time.Duration) time.Duration {
	if retryInterval > 0 {
		// Add random duration between [0, interval] to decrease collision chance
		return retryInterval + time.Duration(rand.Intn(int(retryInterval.Nanoseconds())))
	}
	return 0
}
`