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 (
"context"
"fmt"
"sync"
"time"
"git.solsynth.dev/hypernet/nexus/pkg/nex"
"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 {
n *nex.Conn
Rd *redis.Client
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{
n: conn,
Timeout: timeout,
}
if rdc != nil {
c.Rd = rdc
return c, nil
}
rdb := conn.AllocResource(nex.AllocatableResourceCache)
if rdb == nil {
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")
} else {
c.Rd = client
rdc = client
}
return c, nil