|
|
@@ -4,30 +4,31 @@ import (
|
|
|
"context"
|
|
|
"github.com/redis/go-redis/v9"
|
|
|
"go_zh/config"
|
|
|
+ "sync"
|
|
|
"time"
|
|
|
)
|
|
|
|
|
|
-type RedisServer struct {
|
|
|
+type redisServer struct {
|
|
|
rdb *redis.Client
|
|
|
}
|
|
|
|
|
|
-// 定义单例实例,但不在包级别初始化
|
|
|
-var redisServerInstance *RedisServer
|
|
|
+var (
|
|
|
+ redisInstance *redisServer
|
|
|
+ redisOnce sync.Once
|
|
|
+)
|
|
|
var ctx = context.Background()
|
|
|
|
|
|
-// 使用init函数初始化单例实例
|
|
|
-func init() {
|
|
|
- redisServerInstance = &RedisServer{
|
|
|
- rdb: config.Rdb,
|
|
|
- }
|
|
|
+// GetRedisServerInstance 获取单例实例
|
|
|
+func GetRedisServerInstance() *redisServer {
|
|
|
+ redisOnce.Do(func() {
|
|
|
+ redisInstance = &redisServer{
|
|
|
+ rdb: config.Rdb,
|
|
|
+ }
|
|
|
+ })
|
|
|
+ return redisInstance
|
|
|
}
|
|
|
|
|
|
-// 获取单例实例的方法
|
|
|
-func GetRedisServerInstance() *RedisServer {
|
|
|
- return redisServerInstance
|
|
|
-}
|
|
|
-
|
|
|
-func (r *RedisServer) SetStr(key string, val string, timeout int) bool {
|
|
|
+func (r *redisServer) SetStr(key string, val string, timeout int) bool {
|
|
|
err := r.rdb.Set(ctx, key, val, time.Duration(timeout)*time.Second).Err()
|
|
|
if err != nil {
|
|
|
return false
|
|
|
@@ -35,11 +36,11 @@ func (r *RedisServer) SetStr(key string, val string, timeout int) bool {
|
|
|
return true
|
|
|
}
|
|
|
|
|
|
-func (r *RedisServer) GetStr(key string) string {
|
|
|
+func (r *redisServer) GetStr(key string) string {
|
|
|
+
|
|
|
if key == "" {
|
|
|
return ""
|
|
|
}
|
|
|
- ctx := context.Background()
|
|
|
val, err := r.rdb.Get(ctx, key).Result()
|
|
|
if err != nil {
|
|
|
return ""
|