Prevent from creating multiple redis client

This commit is contained in:
LittleSheep 2025-03-29 15:11:07 +08:00
parent 2c4355257c
commit 1ea5aea6b3

View File

@ -3,24 +3,41 @@ package cachekit
import ( import (
"context" "context"
"fmt" "fmt"
"sync"
"time" "time"
"git.solsynth.dev/hypernet/nexus/pkg/nex" "git.solsynth.dev/hypernet/nexus/pkg/nex"
"github.com/redis/go-redis/v9" "github.com/redis/go-redis/v9"
) )
// The global variable below is used to keep there will only be one redis client exist in a single instance
// Prevent if other DirectAccess™ SDK creating too many redis clients
// And able to recreate the conn with different options
var (
rdc *redis.Client
rdl *sync.Mutex
)
type Conn struct { type Conn struct {
n *nex.Conn n *nex.Conn
Rd *redis.Client Rd *redis.Client
Timeout time.Duration Timeout time.Duration
} }
func NewCaConn(conn *nex.Conn, timeout time.Duration) (*Conn, error) { func NewConn(conn *nex.Conn, timeout time.Duration) (*Conn, error) {
rdl.Lock()
defer rdl.Unlock()
c := &Conn{ c := &Conn{
n: conn, n: conn,
Timeout: timeout, Timeout: timeout,
} }
if rdc != nil {
c.Rd = rdc
return c, nil
}
rdb := conn.AllocResource(nex.AllocatableResourceCache) rdb := conn.AllocResource(nex.AllocatableResourceCache)
if rdb == nil { if rdb == nil {
return nil, fmt.Errorf("unable to allocate resource: cache") return nil, fmt.Errorf("unable to allocate resource: cache")
@ -28,6 +45,7 @@ func NewCaConn(conn *nex.Conn, timeout time.Duration) (*Conn, error) {
return nil, fmt.Errorf("allocated cache resource is not a redis client") return nil, fmt.Errorf("allocated cache resource is not a redis client")
} else { } else {
c.Rd = client c.Rd = client
rdc = client
} }
return c, nil return c, nil