Closed
Description
hi
i use go version 1.21
when i call BeginTx with my time out upper than ping timeout i get " context deadline exceeded " error
tested with mysql 5.7 and 8.0.32-0ubuntu0.20.04.2
tested on windows 11 and linux ( ubuntu 20.04 )
how can fix this error?
package main
import (
"context"
"database/sql"
"log"
"time"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
type MysqlManager struct {
Connection *sql.DB
username string
password string
ip string
port string
dbname string
maxOpenConns int
maxIdleConns int
}
var (
mysqlManagerInstance = MysqlManager{}
err error
Heartbeat bool
connectErrorCount int64 = 0
)
func main() {
go dbConn()
select {}
}
func dbConn(){
db, err := sql.Open("mysql", "root@/?charset=utf8mb4,utf8&collation=utf8mb4_persian_ci&parseTime=true&loc=Local&autocommit=false&timeout=100000s")
if err != nil {
panic(err)
}
mysqlManagerInstance.Connection = db
mysqlManagerInstance.Connection.SetMaxOpenConns(4)
mysqlManagerInstance.Connection.SetMaxIdleConns(1)
mysqlManagerInstance.Connection.SetConnMaxLifetime(time.Minute * 20)
mysqlManagerInstance.Connection.SetConnMaxIdleTime(time.Minute * 10)
go mytest()
go myAction()
}
func Begin() (*sql.Tx, error) {
myctx := context.Background()
myctx, _ = context.WithTimeout(myctx, 1500*time.Millisecond)
return mysqlManagerInstance.Connection.BeginTx(myctx, nil)
}
func mytest() {
for {
ctx := context.Background()
ctx, cancel := context.WithTimeout(context.Background(), 1000*time.Millisecond)
err := mysqlManagerInstance.Connection.PingContext(ctx)
if err != nil {
log.Println(err)
}
cancel()
time.Sleep(time.Second)
}
}
func myAction() {
for {
tx, txErr := Begin()
if txErr != nil {
fmt.Println(txErr)
}
if 1==2 {
tx.Query("update xxxxx set blacklist='0' where id=1111111111 ")
tx.Commit()
}
}
}
Metadata
Metadata
Assignees
Labels
No labels