feat: 网元主机支持redis配置项
This commit is contained in:
61
src/framework/redis/conn.go
Normal file
61
src/framework/redis/conn.go
Normal 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()
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
|
||||
Reference in New Issue
Block a user