当前位置: 首页 > 工具软件 > Go-Redis > 使用案例 >

go-redisAPI操作

堵毅然
2023-12-01
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/go-redis/redis/v9"
	"time"
)

type people struct {
	Name  string
	Age   int
	Aihao []string
	Times string
}

func main() {

	RedisDB2 := redis.NewClient(&redis.Options{
		Addr:     "",
		Password: "", // no password set
		DB:       2,        // use default DB
	})
	ctx := context.Background()

	//==========  字符串string  ===============
	result, err := RedisDB2.Set(ctx, "redis-string", 1, 0).Result()
	fmt.Println(result, err)
	//自增
	RedisDB2.Incr(ctx, "redis-string")
	//自减
	RedisDB2.Decr(ctx, "redis-string")
	//加数
	RedisDB2.IncrBy(ctx, "redis-string", 10)
	//获取过期时间
	ttl := RedisDB2.TTL(ctx, "redis-string")
	fmt.Println(ttl)
	//扫描key
	iter := RedisDB2.Scan(ctx, 0, "redis-*", 10).Iterator()
	for iter.Next(ctx) {
		fmt.Println("keys", iter.Val(), ": val", RedisDB2.Get(ctx, iter.Val()).Val())
	}
	//存结构体
	peo := people{
		Name:  "强月城",
		Age:   18,
		Aihao: []string{"吃饭", "睡觉"},
		Times: "2022-01-10 12:13:14",
	}
	peopleJson, _ := json.Marshal(peo)
	RedisDB2.Set(ctx, "string-people", string(peopleJson), 0)
	marshal, _ := json.Marshal([]string{"1", "11"})
	result, err := RedisDB2.Set(ctx, "array", marshal, 0).Result()
	fmt.Println(result, err)

	//============ 双向列表list =============
	result, err := RedisDB2.RPush(ctx, "redis-list", "element-1").Result()
	RedisDB2.Expire(ctx, "redis-list", -1*time.Minute)

	//左添加
	RedisDB2.LPush(ctx, "redis-list", "element-1").Result()
	RedisDB2.LPush(ctx, "redis-list", "element-2").Result()
	RedisDB2.LPush(ctx, "redis-list", "element-3").Result()
	//右添加
	RedisDB2.RPush(ctx, "redis-list", "element")

	//key不存在不添加
	RedisDB2.LPushX(ctx, "redis-list", "奥术大师多")

	//索引读取
	var str string
	RedisDB2.LIndex(ctx, "redis-list", 0).Scan(&str)
	fmt.Println(str)
	//获取长度
	lLen := RedisDB2.LLen(ctx, "redis-list")
	fmt.Println(lLen)
	//批量读取 左闭 右闭 []
	var value []string
	RedisDB2.LRange(ctx, "redis-list", 0, 100).ScanSlice(&value)
	fmt.Println(len(value))
	//弹出
	var s string
	RedisDB2.LPop(ctx, "redis-list").Scan(&s)
	fmt.Println(s)
	//存结构体
	peo1 := people{
		Name:  "强月城",
		Age:   18,
		Aihao: []string{"吃饭", "睡觉"},
		Times: "2022-01-10 12:13:14",
	}
	peo2 := people{
		Name:  "强月城",
		Age:   18,
		Aihao: []string{"吃饭", "睡觉"},
		Times: "2022-01-10 12:13:14",
	}
	peopleJson1, _ := json.Marshal(peo1)
	peopleJson2, _ := json.Marshal(peo2)
	result, err := RedisDB2.LPush(ctx, "list-peoples", peopleJson1, peopleJson2).Result()
	fmt.Println(result, err)

	//============ hash =============
	//直接存结构体 有bug
	peo1 := people{
		Name:  "强月城",
		Age:   18,
		Aihao: []string{"吃饭", "睡觉"},
		Times: "2022-01-10 12:13:14",
	}
	peoJson, _ := json.Marshal(peo1)
	peoMap := make(map[string]interface{}, 10)
	json.Unmarshal(peoJson, &peoMap)
	result, err := RedisDB2.HSet(ctx, "redis-hmap", peoMap).Result()
	RedisDB2.HSetNX()
	fmt.Println(result, err)
	
	//直接存key value
	RedisDB2.HMSet(ctx, "redis-hmap", "age", 1, "name", "强月城")
	//元素自增
	RedisDB2.HIncrBy(ctx, "redis-hmap", "age", 10)
	//获取所有值
	iter := RedisDB2.HScan(ctx, "redis-hmap", 0, "*", 0).Iterator()
	for iter.Next(ctx) {
		fmt.Println("keys", iter.Val())
	}

	//============ set =============
	peo1 := people{
		Name:  "强月城",
		Age:   18,
		Aihao: []string{"吃饭", "睡觉"},
		Times: "2022-01-10 12:13:14",
	}
	marshal, _ := json.Marshal(peo1)
	RedisDB2.SAdd(ctx, "redis-set", marshal)
	RedisDB2.SAdd(ctx, "redis-set-first", 1, 2, 3, 4, 5)
	RedisDB2.SAdd(ctx, "redis-set-second", 3, 4, 5, 6)
	//交集
	var str []string
	RedisDB2.SInter(ctx, "redis-set-first", "redis-set-second").ScanSlice(&str)
	fmt.Println("交集:", str) //交集: [3 4 5]

	//并集
	var str []string
	RedisDB2.SUnion(ctx, "redis-set-first", "redis-set-second").ScanSlice(&str)
	fmt.Println("并集:", str) //并集: [1 2 3 4 5 6]

	//差集
	var str []string
	RedisDB2.SDiff(ctx, "redis-set-first", "redis-set-second").ScanSlice(&str)
	fmt.Println("查集:", str) //查集: [1 2]

	//随机移除
	var str []string
	RedisDB2.SPopN(ctx, "redis-set-first", 2).ScanSlice(&str)
	fmt.Println(str)

	//============ zset =============

	zset1 := []redis.Z{
		{Score: 10,
			Member: "people-1"},
		{Score: 20,
			Member: "people-2"},
		{Score: 30,
			Member: "people-3"},
		{Score: 00,
			Member: "people-0"},
		{Score: 40,
			Member: "people-4"},
	}
	result, err := RedisDB2.ZAdd(ctx, "redis-zset", zset1...).Result()
	fmt.Println(result, err)

	//加分
	//nx:member必须不存在,才可以设置成功,用于添加。
	//xx:member必须存在,才可以设置成功,用于更新。
	//ch:返回此次操作后,有序集合元素和分数发生变化的个数
	//incr:对score做增加,相当于后面介绍的zincrby
	args := redis.ZAddArgs{
		NX: false,
		XX: false,
		LT: false,
		GT: false,
		Ch: false,
		Members: []redis.Z{
			{
				Score:  10,
				Member: "people-0"}},
	}
	RedisDB2.ZAddArgs(ctx, "redis-zset", args).Result()

	//排序 升序 左闭右闭
	var str []string
	RedisDB2.ZRange(ctx, "redis-zset", 0, 3).ScanSlice(&str)
	fmt.Println(str)
	//排序 降序
	RedisDB2.ZRevRange(ctx, "redis-zset", 0, 3).ScanSlice(&str)
	fmt.Println(str)

	//有条件的排序 包括等于
	var str []string
	param := redis.ZRangeBy{
		Min:    "10", //最小分数
		Max:    "39", //最大分数
		Offset: 1,    //在满足条件的范围,从offset下标处开始取值
		Count:  4,    //查询结果集个数
	}
	RedisDB2.ZRangeByScore(ctx, "redis-zset", &param).ScanSlice(&str)
	fmt.Println(str)

	//返回全部分数
	val := RedisDB2.ZRangeWithScores(ctx, "redis-zset", 0, 10).Val()
	for index, value := range val {
		fmt.Println(index, value.Member, value.Score)
	}
	//返回分数
	val, err := RedisDB2.ZScore(ctx, "redis-zset", "people-1").Result()
	fmt.Println(val, err)
	//返回排名
	val := RedisDB2.ZRevRank(ctx, "redis-zset", "people-5").Val()
	fmt.Println(val)
	//返回总数
	card := RedisDB2.ZCard(ctx, "redis-zset")
	fmt.Println(card)
	//移除 指定
	result, err := RedisDB2.ZRem(ctx, "redis-zset", "people-0").Result()
	fmt.Println(result, err)
	//移除 按分数
	result, err := RedisDB2.ZRemRangeByScore(ctx, "redis-zset", "20", "30").Result()
	fmt.Println(result, err)
	//移除 按排名 降序删
	result, err := RedisDB2.ZRemRangeByRank(ctx, "redis-zset", 0, 1).Result()
	fmt.Println(result, err)
	//移除 按
	i, err := RedisDB2.ZRemRangeByLex(ctx, "redis-zset", "[people-0", "[people-4").Result()
	fmt.Println(i, err)

	//========  管道 =========
	//存
	start := time.Time{}.UnixMilli()
	pipelien := RedisDB2.Pipeline()
	for i := 0; i < 20000; i++ {
		pipelien.LPush(ctx, "redis-pipelien", i)
	}
	exec, errs := pipelien.Exec(ctx)
	fmt.Println(exec, errs)
	end := time.Time{}.UnixMilli()
	fmt.Println("执行时间:", end-start)

	start := time.Time{}.UnixMilli()
	for i := 0; i < 20000; i++ {
		RedisDB2.LPush(ctx, "redis-pipelien", i)
	}
	end := time.Time{}.UnixMilli()
	fmt.Println("执行时间:", end-start)

	//管道
	start := time.Now().UnixMilli()
	pipelien := RedisDB2.Pipeline()
	for i := 0; i < 20; i++ {
		pipelien.LIndex(ctx, "redis-pipelien", int64(i))
	}
	cmders, _ := pipelien.Exec(ctx)
	for i, cmder := range cmders {
		result, _ := cmder.(*redis.StringCmd).Result()
		fmt.Println(i, result)
	}
	end := time.Now().UnixMilli()
	fmt.Println("执行时间:", end-start) //37

	//普通
	start := time.Now().UnixMilli()
	str := make([]string, 20)
	for i := 0; i < 20; i++ {
		result, _ := RedisDB2.LIndex(ctx, "redis-pipelien", int64(i)).Result()
		str[i] = result
	}
	end := time.Now().UnixMilli()
	fmt.Println("执行时间:", end-start) //190

}

 类似资料: