golang使用redis-go操作redis
golang使用redis-go操作redis
此处记录redis-go包连接redis,操作常用str、hash类型的数据。
package main import ( "context" "fmt" "github.com/go-redis/redis/v8" ) var rdb *redis.Client var ctx context.Context = context.Background() func initClient() (err error) { rdb = redis.NewClient(&redis.Options{ Addr: "172.21.0.12:6379", Password: "xxxxxxx", DB: 15, PoolSize: 20, }) _, err = rdb.Ping(ctx).Result() if err != nil { return err } return nil } //str key 存取 func strRedis() { rdb.Set(ctx, "name", "wushaoyu", 0) fmt.Printf("key:%v 设置成功", "name") val, err := rdb.Get(ctx, "age").Result() if err != nil { fmt.Printf("key:%v get err:%v", "age", err) } fmt.Printf("val: %v\n", val) } //Hash key 存取 func hashRedis() { s, err := rdb.HGet(ctx, "user", "firstname").Result() //返回值,报错信息 // s := rdb.HGet(ctx, "user", "firstname").Val() //返回值, 返回单个key的值 if err != nil { fmt.Printf("err: %v\n", err) } fmt.Printf("s: %v\n", s) fmt.Println("========================") m, _ := rdb.HGetAll(ctx, "user").Result() //map[firstname:wu lastname:shao] fmt.Printf("%+v\n", m) // fmt.Printf("m[\"firstname\"]: %v\n", m["firstname"]) // fmt.Printf("m[\"lastname\"]: %v\n", m["lastname"]) } func main() { if err := initClient(); err != nil { fmt.Printf("init redis client failed,err:%v\n", err) return } fmt.Println("connect redis success....")
//程序退出时释放相关资源
defer rdb.Close()
// strRedis() // hashRedis() }