go语言使用redis

go语言使用redis

go-redis库

安装

区别于另一个比较常用的Go语言redis client库:redigo,我们这里采用https://github.com/go-redis/redis连接Redis数据库并进行操作,因为go-redis支持连接哨兵及集群模式的Redis。

使用以下命令下载并安装:

go get -u github.com/go-redis/redis

普通连接

var client *redis.Client

func init() {
	client = redis.NewClient(&redis.Options{Addr: "127.0.0.1:6380", Password: "123456", DB: 2})
	res, err := client.Ping().Result()
	if err != nil {
		fmt.Println("redisutils conn fail:", err)
	}
	fmt.Println("6380 rediskeyword %v", res)
}

注意: 最新版本下Ping()可能需要传递context.Context参数,例如:

rdb.Ping(context.TODO())

连接Redis哨兵模式

func initClient()(err error){
    rdb := redis.NewFailoverClient(&redis.FailoverOptions{
        MasterName:    "master",
        SentinelAddrs: []string{"x.x.x.x:6379", "xx.xx.xx.xx:6379", "xxx.xxx.xxx.xxx:6379"},
    })
    _, err = rdb.Ping().Result()
    if err != nil {
        return err
    }
    return nil
}

连接Redis集群

func initClient()(err error){
    rdb := redis.NewClusterClient(&redis.ClusterOptions{
        Addrs: []string{":7000", ":7001", ":7002", ":7003", ":7004", ":7005"},
    })
    _, err = rdb.Ping().Result()
    if err != nil {
        return err
    }
    return nil
}

基本使用

func redisExample() {
    err := rdb.Set("score", 100, 0).Err()
    if err != nil {
        fmt.Printf("set score failed, err:%v\n", err)
        return
    }

    val, err := rdb.Get("score").Result()
    if err != nil {
        fmt.Printf("get score failed, err:%v\n", err)
        return
    }
    fmt.Println("score", val)

    val2, err := rdb.Get("name").Result()
    if err == redis.Nil {
        fmt.Println("name does not exist")
    } else if err != nil {
        fmt.Printf("get name failed, err:%v\n", err)
        return
    } else {
        fmt.Println("name", val2)
    }
}


func Mgetkeys() map[string]int {
	keys := []string{"showpcreal404", "showpcweb", "showpcweihu", "showpcweibanan", "notshowpagemb", "showad"}
	state, _ := client.MGet(keys...).Result()
	map1 := make(map[string]int)
	for i, val := range keys {
		if state[i] == nil {
			map1[val] = 0
		} else {
			map1[val], _ = strconv.Atoi(state[i].(string))
		}
		//fmt.Println("i=%v val=%v,value=%v", i, val, state[i])
	}
	return map1
}

func redisExample2() {
    zsetKey := "language_rank"
    languages := []redis.Z{
        redis.Z{Score: 90.0, Member: "Golang"},
        redis.Z{Score: 98.0, Member: "Java"},
        redis.Z{Score: 95.0, Member: "Python"},
        redis.Z{Score: 97.0, Member: "JavaScript"},
        redis.Z{Score: 99.0, Member: "C/C++"},
    }
    // ZADD
    num, err := rdb.ZAdd(zsetKey, languages...).Result()
    if err != nil {
        fmt.Printf("zadd failed, err:%v\n", err)
        return
    }
    fmt.Printf("zadd %d succ.\n", num)

    // 把Golang的分数加10
    newScore, err := rdb.ZIncrBy(zsetKey, 10.0, "Golang").Result()
    if err != nil {
        fmt.Printf("zincrby failed, err:%v\n", err)
        return
    }
    fmt.Printf("Golang's score is %f now.\n", newScore)

    // 取分数最高的3个
    ret, err := rdb.ZRevRangeWithScores(zsetKey, 0, 2).Result()
    if err != nil {
        fmt.Printf("zrevrange failed, err:%v\n", err)
        return
    }
    for _, z := range ret {
        fmt.Println(z.Member, z.Score)
    }

    // 取95~100分的
    op := redis.ZRangeBy{
        Min: "95",
        Max: "100",
    }
    ret, err = rdb.ZRangeByScoreWithScores(zsetKey, op).Result()
    if err != nil {
        fmt.Printf("zrangebyscore failed, err:%v\n", err)
        return
    }
    for _, z := range ret {
        fmt.Println(z.Member, z.Score)
    }
}
结果如下:
zadd 0 succ.
Golang's score is 100.000000 now.
Golang 100
C/C++ 99
Java 98
JavaScript 97
Java 98
C/C++ 99
Golang 100

    // 判断key是否存在
    _, err := client.Get(context.Background(), "zngw").Result()
    if err == redis.Nil {
        fmt.Println("key不存在")
    } else {
        fmt.Println("key存在")
    }

    // 设置string
    err = client.Set(context.Background(), "zngw", "hello", 0).Err()
    if err != nil {
        fmt.Println(err)
    }

    // 获取string
    val2, err := client.Get(context.Background(), "zngw").Result()
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println("读取 zngw :", val2)

    // 设置带超时时间的string
    set, err := client.SetNX(context.Background(), "guoke", "hello", 10*time.Second).Result()
    if set {
        fmt.Println("设置成功")
    } else {
        fmt.Println("设置失败")
    }

Hash操作

    // 设置Hash Key
    err = client.HSet(context.Background(), "key", "hash:key", "value").Err()
    if err != nil {
        fmt.Println(err)
    }

    // 获取Hash Key
    val1, err := client.HGet(context.Background(), "key", "hash:key").Result()
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println("读取 zngw :", val1)

    // 获取Key所有键值
    val2, err := client.HGetAll(context.Background(), "key").Result()
    if err != nil {
        fmt.Println(err)
    }

    for k, v := range val2 {
        fmt.Println("key:", k, "value:", v)
    }

批量处理

func batchSet() {
    pipeline := client.Pipeline()
    ctx := context.Background()
    for i := 0; i < 100; i++ {
        key := fmt.Sprintf("%d", i)
        pipeline.HSet(ctx, key, map[string]interface{}{key: key})
    }

    _, err := pipeline.Exec(ctx)
    if err != nil {
        panic(err)
    }
}

func batchGet() {
    pipeline := client.Pipeline()
    ctx := context.Background()
    result := make([]*redis.StringStringMapCmd, 0)
    for i := 0; i < 100; i++ {
        key := fmt.Sprintf("%d", i)
        result = append(result, pipeline.HGetAll(ctx, key))
    }

    _, _ = pipeline.Exec(ctx)
    for _, r := range result {
        v, err := r.Result()
        if err != nil {
            panic(err)
        }

        fmt.Println(v)
    }
}

 

未经允许不得转载:微信 美文-微信文章库-我的知识库 » go语言使用redis

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏

我的知识库