package main

import (
"log"
"sync"
"time" "gopkg.in/mgo.v2"
) var sizeMax = 50
var size = 0
var sizeMu = sync.Mutex{}
var pool = make(chan *mgo.Session, sizeMax) func getConn() *mgo.Session {
sizeMu.Lock()
defer sizeMu.Unlock()
select {
case conn := <-pool:
log.Println("get conn from pool start")
if conn.Ping() == nil {
log.Println("get conn from pool success")
return conn
} else {
size--
}
default:
}
if size >= sizeMax {
log.Println("继续从连接池获取连接")
conn := <-pool
if conn.Ping() == nil {
return conn
} else {
size--
}
}
log.Println("get conn from new")
session, err := mgo.Dial("localhost")
if err != nil {
log.Fatal(err)
}
log.Println("get conn from new success")
size++
return session
} func putConn(conn *mgo.Session) {
pool <- conn
} func main() {
wg := sync.WaitGroup{}
for i := 0; i < 100; i++ {
wg.Add(1)
if i == 3 {
}
go func(n int) {
log.Println("n:", n, "开始连接")
conn := getConn()
time.Sleep(time.Second)
putConn(conn)
log.Println("n:", n, "释放连接")
wg.Done()
}(i)
}
wg.Wait()
log.Println("连接池数量:", len(pool))
}
2018/12/07 22:30:48 n: 1 开始连接
2018/12/07 22:30:48 get conn from new
2018/12/07 22:30:48 n: 0 开始连接
2018/12/07 22:30:48 n: 2 开始连接
2018/12/07 22:30:48 get conn from new success
2018/12/07 22:30:48 n: 1 释放连接
2018/12/07 22:30:48 get conn from new
2018/12/07 22:30:48 get conn from new success
2018/12/07 22:30:48 n: 0 释放连接
2018/12/07 22:30:48 继续从连接池获取连接
2018/12/07 22:30:48 n: 2 释放连接
2018/12/07 22:30:49 n: 9 开始连接
2018/12/07 22:30:49 n: 4 开始连接
2018/12/07 22:30:49 n: 5 开始连接
2018/12/07 22:30:49 get conn from pool start
2018/12/07 22:30:49 get conn from pool start
2018/12/07 22:30:49 n: 6 开始连接
2018/12/07 22:30:49 n: 7 开始连接
2018/12/07 22:30:49 n: 8 开始连接
2018/12/07 22:30:49 n: 3 开始连接
2018/12/07 22:30:49 继续从连接池获取连接
2018/12/07 22:30:49 get conn from pool success
2018/12/07 22:30:49 n: 4 释放连接
2018/12/07 22:30:49 n: 5 释放连接
2018/12/07 22:30:49 继续从连接池获取连接
2018/12/07 22:30:49 n: 6 释放连接
2018/12/07 22:30:49 get conn from pool success
2018/12/07 22:30:49 n: 9 释放连接
2018/12/07 22:30:49 继续从连接池获取连接
2018/12/07 22:30:49 n: 7 释放连接
2018/12/07 22:30:49 继续从连接池获取连接
2018/12/07 22:30:49 n: 8 释放连接
2018/12/07 22:30:49 继续从连接池获取连接
2018/12/07 22:30:49 n: 3 释放连接
2018/12/07 22:30:49 连接池数量: 2
05-12 10:34