加入网络层

This commit is contained in:
2025-06-26 23:57:54 +08:00
parent 53106465ed
commit 0f29dccec4
57 changed files with 1859 additions and 1274 deletions

View File

@@ -0,0 +1,34 @@
package redis
import (
"context"
"fmt"
"github.com/redis/go-redis/v9"
)
var (
cli *redis.Client
Nil = redis.Nil
)
func Init(host string, port int, password string, db int) error {
cli = redis.NewClient(&redis.Options{
Addr: fmt.Sprintf("%s:%d", host, port),
Password: password,
DB: db,
})
_, err := cli.Ping(context.Background()).Result()
return err
}
func Client() *redis.Client {
return cli
}
func Close() error {
if cli != nil {
return cli.Close()
}
return nil
}

View File

@@ -1,57 +0,0 @@
package redis
import (
commonConfig "common/config"
"context"
"crypto/tls"
"errors"
"fmt"
"github.com/redis/go-redis/v9"
"time"
)
var (
redisClient *redis.Client
redisNotInitErr = errors.New("redis is not initialized.")
keyNotExist = errors.New("key does not exist")
Nil = redis.Nil
)
func Init(cfg *commonConfig.RedisConfig) error {
url := fmt.Sprintf("%s:%d", cfg.Host, cfg.Port)
if cfg.Tls {
redisClient = redis.NewClient(&redis.Options{
Addr: url,
Password: cfg.Auth,
DB: cfg.Db,
DialTimeout: 20 * time.Second,
Username: cfg.UserName,
TLSConfig: &tls.Config{},
})
} else {
redisClient = redis.NewClient(&redis.Options{
Addr: url,
Password: cfg.Auth,
DB: cfg.Db,
DialTimeout: 20 * time.Second,
})
}
ret := redisClient.Ping(context.Background())
//p := redisClient.Pipeline()
//l := p.HGetAll(xxx, xxx)
//s := p.Get(xxx, xx)
//p.Exec(xxx)
return ret.Err()
}
func Close() error {
if redisClient != nil {
return redisClient.Close()
}
return nil
}
func GetRedisClient() *redis.Client {
return redisClient
}

View File

@@ -1,37 +0,0 @@
package redis
import (
"common/log"
"context"
"errors"
"time"
)
var ReleaseLockExpire = errors.New("release redis lock expire key")
func Acquire(ctx context.Context, key string, tag string, expiration time.Duration) (bool, error) {
success, err := redisClient.SetNX(ctx, key, tag, expiration).Result()
return success, err
}
func Release(ctx context.Context, key string, tag string) error {
script := `
if redis.call("GET", KEYS[1]) == ARGV[1] then
return redis.call("DEL", KEYS[1])
else
return 0
end`
// 执行 Lua 脚本
result, err := redisClient.Eval(ctx, script, []string{key}, tag).Result()
if err != nil {
return err
}
// 检查返回值
if result == int64(0) {
log.Errorf("release redis lock expire key :%v", key)
return ReleaseLockExpire
}
return nil
}