Be careful #golang# the pitfalls in the official documentation that are not described in detail

Source: Internet
Author: User
Tags new set
This is a created article in which the information may have evolved or changed.

Be careful #golang# the pitfalls in the official documentation that are not described in detail

Recently in high load when using Golang SQL driver encountered leakage problem, finally found Database/sql document and Examples are not very good description of the following 2 key points:

First, each Golang process requires only SQL. Open () once

Initially, it is assumed that SQL is the first to have SQL requests every time. Open (). This is actually wrong. Database/sql itself will maintain the connection pool every time SQL. Open () Creates a new set of connection pools. Although there is no error, it can lead to waste of resources. And I found that when the system resources are tight, it causes the goroutine to release, SQL. Db. Close () also failed to resolve.

Second, after each Query (), be sure to remember Row.close ().

The example of the official Golang document is completely free of code about Row.close (). In fact after Query () Be sure to remember defer rows. Close (). If it is not Close, the row will remain dependent on the SQL connection in the current connection pool and the connection will not be freed. Eventually lead to unnecessary accumulation of resources, or even collapse!

Rows, err: = db. Query ("Select name from the Users WHERE age=?", age)

If err! = Nil {log. Fatal (ERR)}

Defer rows. Close ()//parts not mentioned in the documentation

----

The above two improper uses do not cause the code to error, but when the load is high, a leak occurs. I wish #golang lovers not to repeat my mistakes.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.