golang操作redis主要有两个库,go-redis和redigo
go-redis对函数的封装更简洁, 而且支持连接哨兵及集群模式的Redis

import “github.com/go-redis/redis/v8”

1 连接redisServer

(1) 法一

  1. import "github.com/go-redis/redis/v8"
  2. rdb = redis.NewClient(&redis.Options{
  3. Addr: "localhost:6379",
  4. Password: "", // no password set
  5. DB: 0, // use default DB
  6. })

(2) 法二

  1. opt, err := redis.ParseURL("redis://<user>:<pass>@localhost:6379/<db>")
  2. if err != nil {
  3. panic(err)
  4. }
  5. rdb = redis.NewClient(opt)

2 set/get

  1. func redisExample() {
  2. rdb := RedisClient
  3. err := rdb.Set("score", 100, 0).Err()
  4. if err != nil {
  5. fmt.Printf("set score failed, err:%v\n", err)
  6. return
  7. }
  8. val, err := rdb.Get("score").Result()
  9. if err != nil {
  10. fmt.Printf("get score failed, err:%v\n", err)
  11. return
  12. }
  13. fmt.Println("score", val)
  14. val2, err := rdb.Get("name").Result()
  15. if err == redis.Nil {
  16. fmt.Println("name does not exist")
  17. } else if err != nil {
  18. fmt.Printf("get name failed, err:%v\n", err)
  19. return
  20. } else {
  21. fmt.Println("name", val2)
  22. }
  23. }

3 zset

  1. func redisExample2() {
  2. zsetKey := "language_rank"
  3. languages := []redis.Z{
  4. {Score: 90.0, Member: "Golang"},
  5. {Score: 98.0, Member: "Java"},
  6. {Score: 95.0, Member: "Python"},
  7. {Score: 97.0, Member: "JavaScript"},
  8. {Score: 99.0, Member: "C/C++"},
  9. }
  10. // ZADD
  11. num, err := rdb.ZAdd(zsetKey, languages...).Result()
  12. if err != nil {
  13. fmt.Printf("zadd failed, err:%v\n", err)
  14. return
  15. }
  16. fmt.Printf("zadd %d succ.\n", num)
  17. // 把Golang的分数加10
  18. newScore, err := rdb.ZIncrBy(zsetKey, 10.0, "Golang").Result()
  19. if err != nil {
  20. fmt.Printf("zincrby failed, err:%v\n", err)
  21. return
  22. }
  23. fmt.Printf("Golang's score is %f now.\n", newScore)
  24. // 取分数最高的3个
  25. ret, err := rdb.ZRevRangeWithScores(zsetKey, 0, 2).Result()
  26. if err != nil {
  27. fmt.Printf("zrevrange failed, err:%v\n", err)
  28. return
  29. }
  30. for _, z := range ret {
  31. fmt.Println(z.Member, z.Score)
  32. }
  33. // 取95~100分的
  34. op := redis.ZRangeBy{
  35. Min: "95",
  36. Max: "100",
  37. }
  38. ret, err = rdb.ZRangeByScoreWithScores(zsetKey, op).Result()
  39. if err != nil {
  40. fmt.Printf("zrangebyscore failed, err:%v\n", err)
  41. return
  42. }
  43. for _, z := range ret {
  44. fmt.Println(z.Member, z.Score)
  45. }
  46. }