Jex’s Note

Golang - Redis

redigo

github.com/garyburd/redigo/redis

Connect to redis server

One connection

conn, err := redis.Dial("tcp", ":6379")
if err != nil {
    panic(err)
}
defer conn.Close()

Connection pool

pool := &redis.Pool{
    MaxIdle:     300,               // Maximum number of idle connections in the pool.
    MaxActive:   5,                 // Maximum number of connections allocated by the pool at a given time.
    IdleTimeout: 20 * time.Second,  // Close connections after remaining idle for this duration. Applications should set the timeout to a value less than the server's timeout.
    Dial: func() (redis.Conn, error) {
        c, err := redis.Dial("tcp", "127.0.0.1:6379")
        if err != nil {
            return nil, err
        }
        return c, err
    },
    TestOnBorrow: func(c redis.Conn, t time.Time) error {
        _, err := c.Do("PING")
        return err
    },
}

// 檢查連線是否成功
_, err := pool.Dial()
if err != nil {
    return nil, err
}

Command

GET

val, err := redis.String(conn.Do("GET", "key"))

SET

_, err := conn.Do("SET", workerID, "value")

DEL

_, err := conn.Do("DEL", "key")

LLEN

count, err := redis.Int(conn.Do("LLEN", "list_key"))

LPOP

val, err := redis.Bytes(conn.Do("LPOP", "list_key"))

RPUSH

_, err := conn.Do("RPUSH", "list_key", "val")

HGETALL

res, err = redis.StringMap(conn.Do("HGETALL", "key"))

MHSET

var args []interface{}
args = append(args, "my_hash_key")
for field, val := range hash {
args = append(args, field, val)
}
_, err = conn.Do("HMSET", args...)

or

_, err = conn.Do("HMSET", redis.Args{}.Add("my_hash_key").AddFlat(hash)...)

HGET

val, err = redis.String(conn.Do("HGET", "key", "field"))

HSET

_, err = conn.Do("HSET", key, field, value)

KEYS (show keys with prefix)

vals, err := redis.Values(conn.Do("KEYS", "device:*"))

// 將第一個 key 取出來
_, err := redis.Scan(vals, &value)

其他

如果重覆用同一條 connection 做 del key 的動作可能會引發隨機出現的錯誤

use of closed network connection, short write

原因 : Concurrent writes are not supported

解決方法 : 使用 connection pool,要用的時候就拿一個新的 connection,不用的時候再放回去

Error dial tcp 127.0.0.1:6379: too many open files

使用 pool 要注意取出來的 connection 要釋放, 如果沒釋放有可能會出現此 error,因為系統資源的限制, 一個 process 不能超過 1024 個 socket

redisConn := redisPool.Get()
defer redisConn.Close()

Comments