This is a creation in Article, where the information may have evolved or changed.
Use Redigo this library
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)}}
If the server port is unavailable or service I is unavailable, C. Do returns an error, the port is not available to return connection refused immediately, and the server is unreachable for a period of time before returning. The following code implementation to find the cache first, query failure query MySQL
Type Record struct {key string Val string}func Fetch_key (key String) string {var Val string out: = M Ake (Chan string) Timeout: = Make (chan string, 1)//Timeout Two sec go func () {time. Sleep (2 * time. Second) Timeout <-""} ()//query cache (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 () {//Query database (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 <-"" }//Cache results (Redis), timeout 1 days c.do ("Setex", key,86 400,rec. Val) out <-Rec. Size} out <-' "} ()}//wait for result or timeout sel ECT {Case val = <-timeout:case val = <-out:} return val}