這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
使用Redigo這個庫
package mainimport ("fmt""redis""time""strconv")var (server string = "192.168.1.105:6379"password string = "passwd")var pool *redis.Poolfunc test(i int) {c := pool.Get()defer c.Close()t:=strconv.Itoa(i)c.Do("SETEX","foo"+t,20,i)reply, err := redis.Int(c.Do("GET","foo"+t))if err == nil {fmt.Print(reply)} else {fmt.Print(err)}time.Sleep(1*time.Second)}func poolInit() (*redis.Pool) {//redis poolreturn &redis.Pool{MaxIdle: 3,IdleTimeout: 240 * time.Second,Dial: func () (redis.Conn, error) {c, err := redis.Dial("tcp", server)if err != nil {return nil, err}if _, err := c.Do("AUTH", password); err != nil {c.Close()return nil, err}//if _, err := c.Do("SELECT",1); err != nil {// c.Close()// return nil, err//}return c, err},TestOnBorrow: func(c redis.Conn, t time.Time) error {_, err := c.Do("PING")return err},}}func main() {pool = poolInit()for i:=0;i<1000000;i++ {test(i)}}
如果伺服器連接埠不可用或者服務i不可用,則c.Do會返回錯誤,連接埠不可用立即返回Connection Refused,而伺服器不可達會等待一段時間逾時再返回。下面這段代碼實現先尋找緩衝,查詢失敗時查詢mysql
type Record struct { Key string Val string}func fetch_key(key string) string { var val string out := make(chan string) timeout := make(chan string, 1) //逾時兩秒 go func() { time.Sleep(2 * time.Second) timeout <- "" }() //查詢快取(Redis) c := G_pool.Get() defer c.Close() if reply, err := redis.String(c.Do("GET", key)); err == nil { go func(string) { out <- reply }(reply) } else { go func() { //查詢資料庫(Mysql) db, e := sql.Open("mysql", "username:password@tcp(mysqlip:mysqlport)/dbname?charset=utf8") if e != nil { out <- "" } defer db.Close() rows, e := db.Query("select key,val from dbname.tablename where key=" + key) if e != nil { out <- "" } if rows == nil { out <- "" } for rows.Next() { rec := new(Record) row_err := rows.Scan(&rec.Key,&rec.Val) if row_err != nil { out <- "" } //將結果存入緩衝(Redis),逾時1天 c.Do("SETEX",key,86400,rec.Val) out <- rec.Size } out <- "" }() } //等待結果或者逾時 select { case val = <-timeout: case val = <-out: } return val}