duanduan8439 2018-10-26 02:28
浏览 45


I have a simple Go file with a purpose of returning a json response of a client's information. When I am benchmarking this script with apache benchmark, and the requests are kept alive

ab -t 10s -kc 1000

But when the requests are not kep alive, I do not suffer from this panic

ab -t 10s -c 1000


2018/10/26 03:26:42 http: panic serving Error 1040: Too many connections goroutine 220522 [running]: net/http.(*conn).serve.func1(0xc001779e00)

My code:

package main

import (
    _ "github.com/go-sql-driver/mysql"

type Client struct {
    ID         int    `json:"id"`
    UserID     int    `json:"user_id"`
    Name       string `json:"name"`
    Telephone  string `json:"telephone"`
    Email      string    `json:"email"`
    Category   sql.NullString `json:"string"`
    Notes      string `json:"notes"`
    Additional sql.NullString `json:"additional"`
    CreatedAt  sql.NullString `json:"created_at"`
    UpdatedAt  sql.NullString `json:"updated_at"`
    DeletedAt  sql.NullString `json:"deleted_at"`

func main() {
    r := mux.NewRouter()

    r.HandleFunc("/clients/show/{id}", showClient).Methods("GET")

    http.ListenAndServe(":8080", r)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello World!")

func showClient(w http.ResponseWriter, r *http.Request) {

    db, err := sql.Open("mysql", "root@tcp(")

    if err != nil {

    var client Client

    // Execute the query
    err = db.QueryRow("SELECT * FROM clients where id = ?", 1).Scan(

    if err != nil {



Can someone please explain why this happens at such a low concurrent requests rate and what the correct way to fix this is.

  • 写回答

1条回答 默认 最新

  • dongxing8766 2018-10-26 08:23

    There are two problems, the program use of sockets and the server configuration

    Each connection probably requires 2 sockets, one to the database and one to the http client. Moving the sql.Open() to a different scope so it is not repeatedly called would help with the database sockets. For the http server, the defaults are actually quite low - close connections if there are more than 2 unused keep alives

    Additionally, your server probably needs modification

    As the top answer to this question discusses Increasing the maximum number of tcp/ip connections in linux the default connections per second for Linux are quite conservative and a small simple Go server could well overwealm it

    Tune the server in line with the above answer and that should help

    本回答被题主选为最佳回答 , 对您是否有帮助呢?



  • ¥15 请上面代码做什么处理或什么混淆
  • ¥15 英雄联盟自定义房间置顶
  • ¥15 W5500网线插上无反应
  • ¥15 如何用字典的Key,显示在WPF的xaml中
  • ¥15 weautomate读取Excel表格信息然后填写到网页一直报错,如何解决?
  • ¥15 C#如何在Webview2中获取网页验证码
  • ¥15 esp32烧录失败,具体情况在图片上
  • ¥15 selenium安装报错
  • ¥15 在node.js中无法安装yarn
  • ¥15 python程序修改