Go Redis 开发
redigo库来实现redis的操作:https://github.com/gomodule/redigo
Redis常用操作
示例代码:
package main import ( "github.com/gomodule/redigo/redis" "fmt" "time" ) func initRedis() (dial redis.Conn, err error) { dial, err = redis.Dial("tcp", "172.16.65.183:30001") if err != nil { panic(err) } return dial, nil } func testSetGet(dial redis.Conn) { // 设置一个Key和value dial.Do("set", "abc", "this is a test") // 设置过期时间 dial.Do("expire", "abc", 2) // 读取指定key的value reply, err := dial.Do("get", "abc") str, err := redis.String(reply, err) if err != nil { panic(err) } fmt.Println(str) } func testHSetGet(dial redis.Conn) { key := "abc" value := "this is a book test" // 设置一个hash表来存储 reply, err := dial.Do("hset", "books", key, value) if err != nil { panic(err) } fmt.Println(reply) reply2, err := dial.Do("hget", "books", key) str, err := redis.String(reply2, err) if err != nil { panic(err) } fmt.Println(str) } func testMSetGet(dial redis.Conn) { key := "abc" value := "this is a test book" key2 := "golang" value2 := "this is a golang book" // 一次设置多个key dial.Do("mset", "books", key, value, key2, value2) str, err := redis.Strings(dial.Do("mget", "books",key, key2)) if err != nil { panic(err) } fmt.Println(str) } func main() { dial, _ := initRedis() testSetGet(dial) testHSetGet(dial) testMSetGet(dial) time.Sleep(4 * time.Second) reply, err := dial.Do("get", "abc") str, err := redis.String(reply, err) if err != nil { panic(err) } fmt.Println("get abc", str) defer dial.Close() }
Redis连接池
连接池使用场景
对于一些大对象,或者初始化过程较长的可复用的对象,我们如果每次都new对象出来,那么意味着会耗费大量的时间。
我们可以将这些对象缓存起来,当接口调用完毕后,不是销毁对象,当下次使用的时候,直接从对象池中拿出来即可。
示例代码:
package main import ( "github.com/gomodule/redigo/redis" "time" "fmt" ) func initRedisPool(serverAddr string, passwd string) (pool *redis.Pool) { pool = &redis.Pool{ MaxIdle: 16, MaxActive: 1024, IdleTimeout: 240 * time.Second, Dial: func() (redis.Conn, error) { conn, err := redis.Dial("tcp", serverAddr) if err != nil { return nil, err } if len(passwd) >0 { _, err := conn.Do("auth", passwd) if err != nil { return nil, err } } return conn, nil }, TestOnBorrow: func(c redis.Conn, t time.Time) error { if time.Since(t) < time.Minute { return nil } _, err := c.Do("ping") return err }, } return pool } func testRedisPool() { redisPool := initRedisPool("172.16.65.181:30001", "") // 获取一个redis连接 conn := redisPool.Get() key := "name" value := "golang" conn.Do("hset", "books", key, value) val, err := redis.String(conn.Do("hget", "books", key)) if err != nil { panic(err) } conn.Close() fmt.Println(val) } func main() { testRedisPool() }