當咱們要進行redis操做或者其餘中間件操做的時候,爲了少發起服務端的鏈接,咱們會在main函數外先創建鏈接,以減小服務端的鏈接次數mysql
事實上,不少中間件的鏈接只是一個語法聲明,其實並無進行真正的鏈接,好比下面的代碼git
package main import ( "fmt" "github.com/garyburd/redigo/redis" "github.com/spf13/cast" "math/rand" "time" ) var ( rds, errxx = redis.Dial("tcp", "1.1.1.1:3333") ) func Do(i int) { fmt.Println("開始進行redis操做...") act, err := rds.Do("SET", "name" + cast.ToString(i), i) fmt.Println(act, "--------", err) } func main() { ticker := time.NewTicker(3 * time.Second) defer ticker.Stop() for { select { case <-ticker.C: Do(rand.Intn(1000)) } } }
事實上每個操做redis的時候,都會對redis從新發起一次鏈接,並無起到減小鏈接的做用github
運行上面的程序, 而後觀察redis的數據寫入, 在寫入一些數據以後,咱們中止redis的服務,程序就會報錯golang
use of closed network connection
可見即便是放在main函數外的中間件句柄, 也只是一個聲明(redis, mysql等都是,其餘還沒測試),並無進行真正的鏈接,因此要減小發起鏈接的次數,仍是乖乖的用鏈接池吧。redis