feat: 网元主机支持redis配置项

This commit is contained in:
TsMask
2024-10-16 16:40:11 +08:00
parent 9c10b4873b
commit 717ee894bd
5 changed files with 99 additions and 5 deletions

View File

@@ -0,0 +1,61 @@
package redis
import (
"context"
"fmt"
"strings"
"time"
"github.com/redis/go-redis/v9"
)
// ConnRedis 连接redis对象
type ConnRedis struct {
Addr string `json:"addr"` // 地址
Port int64 `json:"port"` // 端口
User string `json:"user"` // 用户名
Password string `json:"password"` // 认证密码
Database int `json:"database"` // 数据库名称
DialTimeOut time.Duration `json:"dialTimeOut"` // 连接超时断开
Client *redis.Client `json:"client"`
}
// NewClient 创建Redis客户端
func (c *ConnRedis) NewClient() (*ConnRedis, error) {
// IPV6地址协议
if strings.Contains(c.Addr, ":") {
c.Addr = fmt.Sprintf("[%s]", c.Addr)
}
addr := fmt.Sprintf("%s:%d", c.Addr, c.Port)
// 默认等待5s
if c.DialTimeOut == 0 {
c.DialTimeOut = 5 * time.Second
}
// 连接
rdb := redis.NewClient(&redis.Options{
Addr: addr,
// Username: c.User,
Password: c.Password,
DB: c.Database,
DialTimeout: c.DialTimeOut,
})
// 测试数据库连接
if _, err := rdb.Ping(context.Background()).Result(); err != nil {
return nil, err
}
c.Client = rdb
return c, nil
}
// Close 关闭当前Redis客户端
func (c *ConnRedis) Close() {
if c.Client != nil {
c.Client.Close()
}
}

View File

@@ -30,6 +30,15 @@ if tonumber(current) == 1 then
end
return tonumber(current);`)
// 连接Redis实例
func ConnectPush(source string, rdb *redis.Client) {
if rdb == nil {
delete(rdbMap, source)
return
}
rdbMap[source] = rdb
}
// 连接Redis实例
func Connect() {
ctx := context.Background()