clear_redis.go 1.61 KB
Newer Older
hujiebin's avatar
hujiebin committed
1 2 3 4 5 6 7 8 9
package main

import (
	"context"
	"fmt"
	"github.com/go-redis/redis/v8"
	"log"
)

hujiebin's avatar
1  
hujiebin committed
10
const redisAddr = "172.28.16.47:6379" // 替换为你的Redis地址
hujiebin's avatar
hujiebin committed
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27

func main() {
	// 创建Redis客户端
	client := redis.NewClient(&redis.Options{
		Addr: redisAddr,
		DB:   0, // 替换为你的数据库编号
		//Password: "yPyZH1DYMJhrVQgr",
	})

	// 关闭连接
	defer func() {
		if err := client.Close(); err != nil {
			log.Fatalf("Failed to close Redis connection: %v", err)
		}
	}()

	// 获取所有以"user_qps_"为前缀的键
hujiebin's avatar
1  
hujiebin committed
28
	keys, err := getKeysWithPrefix(client, "game:level:points:")
hujiebin's avatar
hujiebin committed
29 30 31 32 33
	if err != nil {
		log.Fatalf("Failed to get keys with prefix: %v", err)
	}
	println(len(keys))

hujiebin's avatar
hujiebin committed
34
	// 谨慎打开-删除所有匹配的键
hujiebin's avatar
1  
hujiebin committed
35 36 37 38
	//err = deleteKeys(client, keys)
	//if err != nil {
	//	log.Fatalf("Failed to delete keys: %v", err)
	//}
hujiebin's avatar
hujiebin committed
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67

	fmt.Println("Cleanup completed.")
}

// 获取所有以特定前缀开头的键
func getKeysWithPrefix(client *redis.Client, prefix string) ([]string, error) {
	ctx := context.Background()
	var cursor uint64
	var keys []string
	var err error

	for {
		var result []string
		result, cursor, err = client.Scan(ctx, cursor, prefix+"*", 1000).Result()
		if err != nil {
			return nil, err
		}

		keys = append(keys, result...)

		if cursor == 0 {
			break
		}
	}

	return keys, nil
}

// 删除指定的键
hujiebin's avatar
hujiebin committed
68
// 谨慎打开删除动作
hujiebin's avatar
hujiebin committed
69
func deleteKeys(client *redis.Client, keys []string) error {
hujiebin's avatar
hujiebin committed
70
	ctx := context.Background()
hujiebin's avatar
hujiebin committed
71

hujiebin's avatar
hujiebin committed
72 73
	for index, key := range keys {
		// 打开del操作
hujiebin's avatar
hujiebin committed
74 75 76 77
		err := client.Del(ctx, key).Err()
		if err != nil {
			return err
		}
hujiebin's avatar
hujiebin committed
78
		log.Printf("key:%v,index:%v\n", key, index)
hujiebin's avatar
hujiebin committed
79 80 81 82
	}

	return nil
}