Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

context deadline exceeded #1528

Closed
parsibox opened this issue Dec 23, 2023 · 1 comment
Closed

context deadline exceeded #1528

parsibox opened this issue Dec 23, 2023 · 1 comment

Comments

@parsibox
Copy link

parsibox commented Dec 23, 2023

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()
		}
	}

}
@methane
Copy link
Member

methane commented Dec 25, 2023

your code looks too ugly and I can not get what you do.
At least, you don't call tx.Commit() nor tx.Rollback().
Your code can not get connection within timeout.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants