Golang中通过go-redis操作Redis

参考地址:https://github.com/go-redis/redis

定义上下文以及连接的相关信息

var ctx = context.Background()
var rdb = redis.NewClient(&redis.Options{
	Addr: "localhost:6379",
})

string

func TestString(t *testing.T)  {
	rdb.Set(ctx, "key", "value", 0)
	result, err := rdb.Get(ctx, "key").Result()
	if err != nil {
		panic(err)
	}
	fmt.Println("key", result)
}

set

func TestSet(t *testing.T)  {
   addCmd := rdb.SAdd(ctx, "set", "s1", "s2", "s3")
   fmt.Println(addCmd)
   stringSliceCmd := rdb.SMembers(ctx, "set")
   for _,v := range stringSliceCmd.Val() {
      fmt.Println(v)
   }
}

zset

可以通过zset实现排行榜的功能

func TestZSet(t *testing.T)  {
   intCmd := rdb.ZAdd(ctx, "zset",
      &redis.Z{Score: 10, Member: "GetcharZp"},
      &redis.Z{Score: 50, Member: "B-zero"},
      &redis.Z{Score: 20, Member: "GetcharMmc"})
   fmt.Println(intCmd)
   zRange := rdb.ZRange(ctx, "zset", 0, 10)
   for _, v := range zRange.Val() {
      fmt.Println(v)
   }
}

hash

func TestHash(t *testing.T)  {
   intCmd := rdb.HSet(ctx, "hash", map[string]string{"k1": "v1", "k2": "v2", "k3": "v3"})
   fmt.Println(intCmd)
   // 通过指定map中的key获取值
   getOne := rdb.HGet(ctx, "hash", "k1")
   fmt.Println(getOne.Val())
   all := rdb.HGetAll(ctx, "hash")
   for key, value := range all.Val() {
      fmt.Println("key --> ", key, " value --> ", value)
   }
}

list

func TestList(t *testing.T)  {
   intCmd := rdb.LPush(ctx, "list", "l1", "l2", "l3")
   fmt.Println(intCmd)
   lRange := rdb.LRange(ctx, "list", 0, 3) // 从最左边开始取数据
   for _, v := range lRange.Val() {
      fmt.Println(v)
   }
}
posted @ 2022-01-24 14:23  GetcharZp  阅读(421)  评论(0编辑  收藏  举报