douxiapi4381 2016-08-30 11:58
浏览 599
已采纳

SetMaxOpenConns()无法解决“错误1040:连接过多”

I am using golang with Mysql. I am testing load on server using apache benchmark tool. I am getting too many connections error. I read this post . So, I added SetMaxOpenConns(100) in my code. Still I am getting this too many connections error.

I am doing the following query

ab -n 1000 -k -c 20 -p post.txt -T application/x-www-form-urlencoded http://localhost:8084/abcd

Note: post.txt file contains array of 35 ids(type integer). This is my main function:

db, err := models.NewDB("root:@/rules")
    if err != nil {
        panic(err)
    }

    db.SetMaxOpenConns(100)
    http.Handle("/abcd", getReq(db))

    log.Fatal(http.ListenAndServe(":8084", nil))

I am querying this function in go routine for all the ids.

func getRuleforProduct(db *sql.DB, id int) map[int]string {
    m := make(map[int]string)
    var res string
    err := db.QueryRow("select rules from table where product_id = ?", id).Scan(&res)
    checkError(err)
    m[id] = res
    return m
}

How to solve this issue, even if request per second is less. I want the code to work for atleast 20 concurrent request.

  • 写回答

1条回答 默认 最新

  • dpoppu4300 2016-08-31 13:44
    关注

    First you should check how many open connections does your MySQL server allow with SHOW VARIABLES LIKE 'max_connections'. Default is 151 but if it's less than 100 then your program obviously tries to open too many connections.

    But even if it's more than 100 you could still easily get that error. MySQL's max_connections is a global variable that affects the whole server. If your program uses other databases on same server they will also count towards your max_connections limit. Or similarly if you have other programs using your database server you can also run out of connections. In that case you have to use smaller values for SetMaxOpenConns() or increase the max_connections variable.

    Also consider setting db.SetMaxIdleConns() To a value lower than db.SetMaxOpenConns(). Otherwise you might have 100 (or whatever value you gave to SetMaxOpenConns) idle connections to your database server using up your connection pool.

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

报告相同问题?

悬赏问题

  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi