search
HomeBackend DevelopmentGolangTake you to understand golang mysql database connection pool

Take you to understand golang mysql database connection pool

May 11, 2021 am 11:32 AM
goDatabase connection pool

The following is an introduction to the golang mysql database connection pool from the golang tutorial column. I hope it will be helpful to friends in need!

Recently, I was using the go language ORM to do some database operations. Finally, I found a bug called invalid connection, so I went to learn about the timeout of the connection pool and mysql. Next, I will use the go ORM. mysql to illustrate (I understand that the languages ​​​​are all connected, and the principles should be the same).

When we want to add, delete, modify and check the database, the first step is to connect to the database

//conn the database
func ConnDb(dbConnString string, dbName string) error {
	maxIdle := 50
	maxConn := 50
	err := orm.RegisterDataBase(dbName, "mysql", dbConnString+"?charset=utf8&loc=Asia%2FShanghai", maxIdle, maxConn)

	if err != nil {
		util.GLogger.Errorw("in Connect DB", "err", err)
	}
	return err
}

The connection here is the mysql database. The maximum connection pool set is 50. The maximum The number of idle connections is 50.

What does this connection pool mainly do? To put it simply, if you want to get data from the database and change the data, you need to establish a pipeline with the database. This is to establish a network connection. We all know that TCP connections are time-consuming, so since it has taken a certain amount of time I've built this pipeline, so how can I take it and use it without throwing it away? Then the connection pool is where these established pipes are stored. The value of 50 can be simply understood as a maximum of 50 pipes. Note that the bigger the better, because if it is too large, it will occupy more memory. Of course, it will take up too much memory. If it is too small, there will be waiting for blocking.

Since these pipes are placed in the connection pool, then the idle connection refers to these idle pipes, then it is obvious that the value setting of the idle connection should not be larger than the size of the connection pool, because the larger the connection The pool will not help you save so many idle connection pipes.

After understanding these simple concepts, what is the workflow like every time you access the database?

#Through this diagram we can clearly see the entire connection access process.

step1 (Get available connections) Go to the connection pool to find available idle connections. If there are no idle connections, then determine whether the connection pool is full. If not, then create a new connection. , if it is full, then wait for the connection to be released; of course, if there is an idle connection, it will directly determine whether the connection has expired. If it has not expired, it will be used directly. If it expires, it will re-judge whether the connection pool is full. No If so, create a new connection and wait when it is full.

step2 (Operation database) After getting this connection, perform addition, deletion, modification and query operations.

step3 (Release connection) After operating the database, you need to release the connection, then the released connection will become idle. If it exceeds the number of idle connections, it will be closed directly. If not, it will be used for waiting.

Then you will notice that this connection will fail:

The timeout of mysql database, when you establish a connection with the database, the database cannot always trust you, then the database There is a timeout, that is, after this period of time, I will not trust your connection. You must connect to me again. Check the various timeout statements set by the database as follows:

show variables like  '%timeout%';

Among them There will be two timeouts: interactive connection timeout (interactive_timeout) and non-interactive connection timeout (wait_timeout)

Interactive connection: you connect to mysql through the command line

Non-interactive connection: It is to connect to mysql in the program

And this non-interactive timeout is when the idle time of the idle connection in the connection pool exceeds the wait_timeout setting. Then at this time, when the program gets the idle connection and makes a query, the original problem will appear, invalid connection.

After understanding the basic principles, the solution to invalid connection is very simple:

1. Extend the wait_timeout time of the database.

2. The program regularly checks these failed connections and discards them in time. Note that the checking time of the program here needs to be less than the wait_timeout value set by mysql.

The above is my understanding of the connection pool. If there are any mistakes, please point them out. Thank you~

The above is the detailed content of Take you to understand golang mysql database connection pool. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:csdn. If there is any infringement, please contact admin@php.cn delete
Learn Go String Manipulation: Working with the 'strings' PackageLearn Go String Manipulation: Working with the 'strings' PackageMay 09, 2025 am 12:07 AM

Go's "strings" package provides rich features to make string operation efficient and simple. 1) Use strings.Contains() to check substrings. 2) strings.Split() can be used to parse data, but it should be used with caution to avoid performance problems. 3) strings.Join() is suitable for formatting strings, but for small datasets, looping = is more efficient. 4) For large strings, it is more efficient to build strings using strings.Builder.

Go: String Manipulation with the Standard 'strings' PackageGo: String Manipulation with the Standard 'strings' PackageMay 09, 2025 am 12:07 AM

Go uses the "strings" package for string operations. 1) Use strings.Join function to splice strings. 2) Use the strings.Contains function to find substrings. 3) Use the strings.Replace function to replace strings. These functions are efficient and easy to use and are suitable for various string processing tasks.

Mastering Byte Slice Manipulation with Go's 'bytes' Package: A Practical GuideMastering Byte Slice Manipulation with Go's 'bytes' Package: A Practical GuideMay 09, 2025 am 12:02 AM

ThebytespackageinGoisessentialforefficientbyteslicemanipulation,offeringfunctionslikeContains,Index,andReplaceforsearchingandmodifyingbinarydata.Itenhancesperformanceandcodereadability,makingitavitaltoolforhandlingbinarydata,networkprotocols,andfileI

Learn Go Binary Encoding/Decoding: Working with the 'encoding/binary' PackageLearn Go Binary Encoding/Decoding: Working with the 'encoding/binary' PackageMay 08, 2025 am 12:13 AM

Go uses the "encoding/binary" package for binary encoding and decoding. 1) This package provides binary.Write and binary.Read functions for writing and reading data. 2) Pay attention to choosing the correct endian (such as BigEndian or LittleEndian). 3) Data alignment and error handling are also key to ensure the correctness and performance of the data.

Go: Byte Slice Manipulation with the Standard 'bytes' PackageGo: Byte Slice Manipulation with the Standard 'bytes' PackageMay 08, 2025 am 12:09 AM

The"bytes"packageinGooffersefficientfunctionsformanipulatingbyteslices.1)Usebytes.Joinforconcatenatingslices,2)bytes.Bufferforincrementalwriting,3)bytes.Indexorbytes.IndexByteforsearching,4)bytes.Readerforreadinginchunks,and5)bytes.SplitNor

Go encoding/binary package: Optimizing performance for binary operationsGo encoding/binary package: Optimizing performance for binary operationsMay 08, 2025 am 12:06 AM

Theencoding/binarypackageinGoiseffectiveforoptimizingbinaryoperationsduetoitssupportforendiannessandefficientdatahandling.Toenhanceperformance:1)Usebinary.NativeEndianfornativeendiannesstoavoidbyteswapping.2)BatchReadandWriteoperationstoreduceI/Oover

Go bytes package: short reference and tipsGo bytes package: short reference and tipsMay 08, 2025 am 12:05 AM

Go's bytes package is mainly used to efficiently process byte slices. 1) Using bytes.Buffer can efficiently perform string splicing to avoid unnecessary memory allocation. 2) The bytes.Equal function is used to quickly compare byte slices. 3) The bytes.Index, bytes.Split and bytes.ReplaceAll functions can be used to search and manipulate byte slices, but performance issues need to be paid attention to.

Go bytes package: practical examples for byte slice manipulationGo bytes package: practical examples for byte slice manipulationMay 08, 2025 am 12:01 AM

The byte package provides a variety of functions to efficiently process byte slices. 1) Use bytes.Contains to check the byte sequence. 2) Use bytes.Split to split byte slices. 3) Replace the byte sequence bytes.Replace. 4) Use bytes.Join to connect multiple byte slices. 5) Use bytes.Buffer to build data. 6) Combined bytes.Map for error processing and data verification.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software