How do I share a MySQL connection across multiple HTTP goroutines in Go?

Linda Hamilton
Release: 2024-11-10 09:56:02
Original
546 people have browsed it

How do I share a MySQL connection across multiple HTTP goroutines in Go?

Sharing MySQL Connections in Go HTTP Goroutines

When working with HTTP goroutines in Go, it's essential to optimize performance by sharing database connections. This article demonstrates how to establish and share a MySQL connection among multiple HTTP handlers.

Database Connection Management

In Go, the database/sql package handles connection pooling automatically. When calling sql.Open(...), a connection pool is created rather than a single connection. This means that the database/sql package will automatically obtain a connection from the pool if all connections are already in use.

Code Implementation

To share a MySQL connection in your HTTP goroutines, follow these steps:

  1. Initialize the Database Connection:

    • Open a connection pool using sql.Open("mysql", "").

    Example:

    db, err := sql.Open("mysql", "root:@/mydb?charset=utf8")
    if err != nil {
        log.Fatalf("Error opening database: %v", err)
    }
    Copy after login
  2. Configure Connection Pooling:

    • Adjust the maximum number of idle connections using db.SetMaxIdleConns(100).
  3. Share the Connection Handle:

    • Declare the db variable as a global variable to share it between main and HTTP handlers.

    Example:

    var db *sql.DB
    Copy after login
  4. Check Database Connection:

    • Call db.Ping() in main() to establish an initial connection to the database.

    Example:

    err = db.Ping()
    if err != nil {
        log.Fatalf("Error opening database connection: %s", err.Error())
    }
    Copy after login
  5. Use Connection in HTTP Handlers:

    • In the HTTP handler, use the shared db handle to execute database queries.

    Example:

    func HomeHandler(w http.ResponseWriter, r *http.Request) {
        var msg string
        err := db.QueryRow("SELECT msg FROM hello WHERE page=?", "home").Scan(&msg)
        if err != nil {
            fmt.Fprintf(w, "Database Error!")
        } else {
            fmt.Fprintf(w, msg)
        }
    }
    Copy after login

By following these steps, you can efficiently share a MySQL connection across multiple HTTP goroutines without compromising performance.

The above is the detailed content of How do I share a MySQL connection across multiple HTTP goroutines in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template