2025-05-10 16:59:41 +08:00
|
|
|
package globals
|
2025-03-18 17:57:07 +08:00
|
|
|
|
|
|
|
|
import (
|
2025-06-26 09:28:42 +08:00
|
|
|
"log/slog"
|
2025-03-18 17:57:07 +08:00
|
|
|
"net"
|
2025-03-26 14:57:44 +08:00
|
|
|
"platform/pkg/env"
|
2025-06-26 09:28:42 +08:00
|
|
|
"platform/web/core"
|
2025-03-18 17:57:07 +08:00
|
|
|
|
2025-11-17 18:38:10 +08:00
|
|
|
"github.com/go-redsync/redsync/v4/redis/goredis/v9"
|
|
|
|
|
|
2025-05-27 15:08:18 +08:00
|
|
|
"github.com/go-redsync/redsync/v4"
|
2025-03-18 17:57:07 +08:00
|
|
|
"github.com/redis/go-redis/v9"
|
|
|
|
|
)
|
|
|
|
|
|
2025-05-10 16:59:41 +08:00
|
|
|
var Redis *redis.Client
|
2025-06-26 09:28:42 +08:00
|
|
|
var Redsync *ExtendRedSync
|
|
|
|
|
|
|
|
|
|
type ExtendRedSync struct {
|
|
|
|
|
*redsync.Redsync
|
|
|
|
|
}
|
2025-03-18 17:57:07 +08:00
|
|
|
|
2025-11-17 18:38:10 +08:00
|
|
|
func initRedis() error {
|
2025-05-27 15:08:18 +08:00
|
|
|
client := redis.NewClient(&redis.Options{
|
2025-03-18 17:57:07 +08:00
|
|
|
Addr: net.JoinHostPort(env.RedisHost, env.RedisPort),
|
2025-11-17 18:38:10 +08:00
|
|
|
Password: env.RedisPassword,
|
2025-03-18 17:57:07 +08:00
|
|
|
})
|
2025-05-27 15:08:18 +08:00
|
|
|
|
|
|
|
|
pool := goredis.NewPool(client)
|
|
|
|
|
sync := redsync.New(pool)
|
|
|
|
|
|
|
|
|
|
Redis = client
|
2025-06-26 09:28:42 +08:00
|
|
|
Redsync = &ExtendRedSync{sync}
|
2025-11-17 18:38:10 +08:00
|
|
|
|
|
|
|
|
return nil
|
2025-03-18 17:57:07 +08:00
|
|
|
}
|
2025-04-01 11:26:37 +08:00
|
|
|
|
2025-12-01 19:31:45 +08:00
|
|
|
func closeRedis() error {
|
2025-05-10 16:59:41 +08:00
|
|
|
if Redis != nil {
|
|
|
|
|
return Redis.Close()
|
2025-04-01 11:26:37 +08:00
|
|
|
}
|
|
|
|
|
return nil
|
|
|
|
|
}
|
2025-06-26 09:28:42 +08:00
|
|
|
|
|
|
|
|
func (r *ExtendRedSync) WithLock(key string, callback func() error) error {
|
|
|
|
|
var mutex = Redsync.NewMutex(key)
|
|
|
|
|
var err = mutex.Lock()
|
|
|
|
|
if err != nil {
|
|
|
|
|
return core.NewServErr("服务繁忙,请稍后重试")
|
|
|
|
|
}
|
|
|
|
|
defer func(mutex *redsync.Mutex) {
|
|
|
|
|
if ok, err := mutex.Unlock(); err != nil {
|
|
|
|
|
slog.Error("解锁失败", slog.Bool("ok", ok), slog.Any("err", err))
|
|
|
|
|
}
|
|
|
|
|
}(mutex)
|
|
|
|
|
|
|
|
|
|
return callback()
|
|
|
|
|
}
|