diff --git a/README.md b/README.md index 6868d9d..3b3a126 100644 --- a/README.md +++ b/README.md @@ -33,4 +33,19 @@ result,err := caches.Delete("key2") // Delete More result,err = caches.Delete("key2","key3","key4") + +// already redis connect client +rdsClient := redis.NewClient(&redis.Options{ + Addr: fmt.Sprintf("%s:%s", "192.168.0.151", "6379"), + Password: "", + DB: 15, +}) + +// WithRedisClient() 使用已有的redis链接客户端 +// WithOriginDB() 是否使用已经的客户端的数据库 true - 使用已有的客户端链接数据库 | false - 使用WithDB()中的数据库,如果为空默认使用0库 +// WithDB() 指定数据库,如果 WithOriginDB() 为false,WithDB()未指定的话默认使用0号库 + +caches := NewCache(WithRedisClient(rdsClient), WithOriginDB(true), WithDB(11)) + + ``` \ No newline at end of file diff --git a/cache.go b/cache.go index 70acf08..561bb0e 100644 --- a/cache.go +++ b/cache.go @@ -8,11 +8,12 @@ import ( ) type config struct { - Host string - Port string - Password string - DB int - Client *redis.Client + Host string // redis主机 + Port string // redis 端口 + Password string // redis 密码 + DB int // redis库名 + Client *redis.Client // redis链接客户端 【如果项目中已经有了redis链接可使用该参数】 + OriginDB bool // 是否强制使用redis客户端【Client】的DB } type Option func(ca *config) @@ -47,6 +48,12 @@ func WithDB(db int) Option { } } +func WithOriginDB(originDB bool) Option { + return func(ca *config) { + ca.OriginDB = originDB + } +} + type Cache interface { // Put 放入缓存 Put(key string, value interface{}, ttl time.Duration) error @@ -81,6 +88,9 @@ func NewCache(opts ...Option) Cache { }) } else { rClient.client = cha.Client + if cha.OriginDB == false { + rClient.client.Options().DB = cha.DB + } } rClient.ctx = context.Background() diff --git a/cache_test.go b/cache_test.go index 3a93589..eafe242 100644 --- a/cache_test.go +++ b/cache_test.go @@ -2,6 +2,7 @@ package rds_cache_go import ( "fmt" + "github.com/go-redis/redis/v8" "testing" "time" ) @@ -36,3 +37,15 @@ func TestCache_Delete(t *testing.T) { resunt := caches.Delete("key1", "key2") fmt.Println(resunt) } + +func TestCache_RdsClient(t *testing.T) { + client := redis.NewClient(&redis.Options{ + Addr: fmt.Sprintf("%s:%s", "192.168.0.151", "6379"), + Password: "", + DB: 15, + }) + + cachess := NewCache(WithRedisClient(client), WithOriginDB(true), WithDB(11)) + + cachess.Put("this key", "this aaaaa", 1*time.Minute) +}