u
This commit is contained in:
1 parent
5a79414319
commit
8663cb2e3d
28 files changed
+744
-756
No files matched your search
@@ -0,0 +1,27 @@
|
||||
package redisx
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Set 设置 key
|
||||
func Set(ctx context.Context, key string, value any, ttl time.Duration) error {
|
||||
return Client().Set(ctx, key, value, ttl).Err()
|
||||
}
|
||||
|
||||
// Get 获取 string
|
||||
func Get(ctx context.Context, key string) (string, error) {
|
||||
return Client().Get(ctx, key).Result()
|
||||
}
|
||||
|
||||
// Del 删除
|
||||
func Del(ctx context.Context, keys ...string) error {
|
||||
return Client().Del(ctx, keys...).Err()
|
||||
}
|
||||
|
||||
// Exists 是否存在
|
||||
func Exists(ctx context.Context, key string) (bool, error) {
|
||||
n, err := Client().Exists(ctx, key).Result()
|
||||
return n > 0, err
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package redisx
|
||||
|
||||
import (
|
||||
"allapp/conf"
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
var (
|
||||
client *redis.Client
|
||||
once sync.Once
|
||||
)
|
||||
|
||||
// Init 初始化 Redis(只会执行一次)
|
||||
func Init() *redis.Client {
|
||||
once.Do(func() {
|
||||
redisConfig := conf.GetConf().Redis
|
||||
|
||||
addr := fmt.Sprintf("%s:%d", redisConfig.Host, redisConfig.Port)
|
||||
|
||||
client = redis.NewClient(&redis.Options{
|
||||
Addr: addr,
|
||||
Password: redisConfig.Password,
|
||||
DB: redisConfig.Db,
|
||||
})
|
||||
|
||||
// 启动时检测连接
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if err := client.Ping(ctx).Err(); err != nil {
|
||||
panic("redis 连接失败: " + err.Error())
|
||||
}
|
||||
})
|
||||
|
||||
return client
|
||||
}
|
||||
|
||||
// Client 获取 Redis 客户端
|
||||
func Client() *redis.Client {
|
||||
if client == nil {
|
||||
panic("redis 尚未初始化")
|
||||
}
|
||||
return client
|
||||
}
|
||||
Reference in new issue
Block a user