github.com/wfusion/gofusion@v1.1.14/redis/redis.go (about)

     1  package redis
     2  
     3  import (
     4  	"context"
     5  	"sync"
     6  
     7  	"github.com/pkg/errors"
     8  
     9  	"github.com/wfusion/gofusion/common/infra/drivers/redis"
    10  	"github.com/wfusion/gofusion/common/utils"
    11  
    12  	rdsDrv "github.com/redis/go-redis/v9"
    13  )
    14  
    15  var (
    16  	rwlock       = new(sync.RWMutex)
    17  	appInstances map[string]map[string]*instance
    18  )
    19  
    20  type instance struct {
    21  	name  string
    22  	redis *redis.Redis
    23  }
    24  
    25  func (i *instance) GetProxy() rdsDrv.UniversalClient {
    26  	return i.redis.GetProxy()
    27  }
    28  
    29  type Redis struct {
    30  	rdsDrv.UniversalClient
    31  	Name string
    32  }
    33  
    34  type useOption struct {
    35  	appName string
    36  }
    37  
    38  func AppName(name string) utils.OptionFunc[useOption] {
    39  	return func(o *useOption) {
    40  		o.appName = name
    41  	}
    42  }
    43  
    44  func Use(ctx context.Context, name string, opts ...utils.OptionExtender) rdsDrv.UniversalClient {
    45  	opt := utils.ApplyOptions[useOption](opts...)
    46  
    47  	rwlock.RLock()
    48  	defer rwlock.RUnlock()
    49  	instances, ok := appInstances[opt.appName]
    50  	if !ok {
    51  		panic(errors.Errorf("redis instance not found for app: %s", opt.appName))
    52  	}
    53  	instance, ok := instances[name]
    54  	if !ok {
    55  		panic(errors.Errorf("redis instance not found for name: %s", name))
    56  	}
    57  	return &Redis{UniversalClient: instance, Name: name}
    58  }