Golang use of Redis connection pooling
Last Update:2018-01-18
Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed. "'" Golangpackage mainimport ("Encoding/json" "Errors" "FMT" "Time" "Github.com/garyburd/redigo/redis") const ( Redisurl = "redis://*****:6379" Redismaxidle = 3//maximum number of idle connections redisidletimeoutsec = 240//maximum idle connection time Redispassword = "* * * *")//N Ewredispool returns the Redis connection pool func newredispool (Redisurl string) *redis. Pool {return &redis. Pool{maxidle:redismaxidle,idletimeout:redisidletimeoutsec * time. Second,dial:func () (Redis. Conn, error) {c, err: = Redis. Dialurl (Redisurl) if err! = Nil {return nil, fmt. Errorf ("Redis connection error:%s", err)}//Verify Redis Password If _, Autherr: = C.do ("AUTH", Redispassword); Autherr! = Nil {return nil, fmt. Errorf ("Redis auth password Error:%s", Autherr)}return C, Err},testonborrow:func (c Redis. Conn, T time. Time) Error {_, Err: = C.do ("PING") if err! = Nil {return FMT. Errorf ("Ping Redis Error:%s", err)}return Nil},}}func set (k, v string) {c: = Newredispool (Redisurl). Get () Defer c.close () _, Err: = C.do ("SET", K, v) if err! = Nil {fmt. PRINTLN ("Set Error", Err.)Error ())}}func GetStringValue (k string) string {c: = Newredispool (Redisurl). Get () defer c.close () Username, err: = Redis. String (C.do ("GET", K)) if err! = Nil {fmt. Println ("Get Error:", err.) Error ()) return "" "}return username}func Setkeyexpire (k string, ex int) {c: = Newredispool (Redisurl). Get () Defer c.close () _, Err: = C.do ("EXPIRE", K, ex) if err! = Nil {fmt. PRINTLN ("Set Error", Err.) Error ())}}func Checkkey (k string) bool {c: = Newredispool (Redisurl). Get () defer c.close () exist, err: = Redis. Bool (C.do ("EXISTS", K)) if err! = Nil {fmt. PRINTLN (ERR) return false} else {return Exist}}func Delkey (k string) error {c: = Newredispool (Redisurl). Get () Defer c.close () _, Err: = C.do ("DEL", K) if err! = Nil {fmt. PRINTLN (ERR) return Err}return nil}func Setjson (k string, data interface{}) error {c: = Newredispool (Redisurl). Get () defer c.close () value, _: = json. Marshal (data) n, _: = C.do ("Setnx", K, value) if n! = Int64 (1) {return errors. New ("Set failed")}return nil}func getjsonbyte (k string) ([]byte, error) {Jsonget, err: = Redis. Bytes (C.do ("GET", key)) if err! = Nil {fmt. PRINTLN (ERR) return nil, Err}return jsonget, nil} ' ' 642 reads