Files
TgLink/lib/redis.go
2025-09-12 16:42:10 +08:00

70 lines
1.5 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package lib
import (
"context"
"fmt"
"github.com/go-redis/redis/v8"
"sync/atomic"
)
var (
rdb *redis.Client
ctx = context.Background()
counter uint64
)
// 初始化 Redis 客户端
func init() {
rdb = redis.NewClient(&redis.Options{
Addr: "127.0.0.1:6379",
Password: "WKJXXmPchENCYK7x",
DB: 2,
})
}
func GetAllLinks() ([]string, error) {
// 使用 LRange 获取整个列表,范围为 0 到 -1表示获取所有元素
links, err := rdb.LRange(ctx, "links", 0, -1).Result()
if err != nil {
return nil, err
}
return links, nil
}
// 添加链接到 Redis List
func AddLink(link string) error {
return rdb.LPush(ctx, "links", link).Err()
}
// 删除指定的链接
func DeleteLink(link string) error {
// LREM count 参数为 0 表示删除所有匹配的元素
return rdb.LRem(ctx, "links", 0, link).Err()
}
// 修改指定索引位置的链接
func UpdateLink(index int64, newLink string) error {
return rdb.LSet(ctx, "links", index, newLink).Err()
}
func GetLink() (string, error) {
length, err := rdb.LLen(ctx, "links").Result()
if err != nil || length == 0 {
return "", fmt.Errorf("no available links")
}
index := atomic.AddUint64(&counter, 1) % uint64(length)
return rdb.LIndex(ctx, "links", int64(index)).Result()
}
func ClearRedis() string {
// 清空当前数据库中的所有数据
err := rdb.FlushDB(ctx).Err()
if err != nil {
mes := fmt.Sprintf("无法清空链接: %v", err)
return mes
} else {
return "成功清空链接,请即使新增链接"
}
}