优化

This commit is contained in:
coward 2021-12-14 17:01:43 +08:00
parent 28f36b50ff
commit a0caf16ba9
3 changed files with 43 additions and 5 deletions

View File

@ -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() 为falseWithDB()未指定的话默认使用0号库
caches := NewCache(WithRedisClient(rdsClient), WithOriginDB(true), WithDB(11))
```

View File

@ -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()

View File

@ -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)
}