douliexu5623 2017-06-15 06:41
浏览 94
已采纳

多重并发时如何解决TIME_WAIT状态问题?

If I run below example on Windows I will quickly hit TCP connection limit (which I set to 64k) and get error: dial tcp 127.0.0.1:3306: connectex: Only one usage of each socket address (protocol/network address/port) is normally permitted.

I see all this TIME_WAIT states waiting for there lifetime to end with: netstat -ano|findstr 3306

Why aren't connections closed immediately?

The code:

package main

import (
    _ "github.com/go-sql-driver/mysql"
    "github.com/jmoiron/sqlx"
    "log"
    "sync"
)

var (
    db_instance *sqlx.DB
    wg          sync.WaitGroup
)

func main() {
    db, err := sqlx.Connect("mysql", "user:pass@/table")
    if err != nil {
        log.Fatalln(err)
    }
    defer db.Close()
    db_instance = db

    for {
        for l := 0; l < 50; l++ {
            wg.Add(1)
            go DB_TEST()
        }
        wg.Wait()
    }
}

func DB_TEST() {
    defer wg.Done()

    var s string
    err := db_instance.QueryRow("SELECT NOW()").Scan(&s)
    if err != nil {
        log.Println(err)
        return
    }
    log.Println(s)
}
  • 写回答

1条回答 默认 最新

  • duanlvxi8652 2017-06-15 08:52
    关注

    Drafting answer from my comments discussion with @Glavić.

    Utilize the SetMaxOpenConns and SetMaxIdleConns settings to keep TIME_WAIT status and connections under control. If needed use SetConnMaxLifetime too, generally it's not needed.

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

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记