是的,您可以通过对两个包以及 set 和 get 操作使用公共 Codec 实例来访问同一个映射。为此,您需要实现一个单例实例生产者。理想情况下,它应该是线程安全的实现。这样,您将节省大量资源并保证连接正确性。这对于保持客户端唯一以防止错误和节省资源非常重要。
Client 是一个 Redis 客户端,代表零个或多个底层连接池。多个 goroutine 并发使用是安全的。
单一编解码器
package singleton
import (
"sync"
"gopkg.in/go-redis/cache.v5"
"gopkg.in/redis.v5"
)
var codec *cache.Codec
var once sync.Once
func GetInstance() *cache.Codec {
once.Do(func() {
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password set
DB: 0, // use default DB
})
codec = &cache.Codec{
Redis: client,
Marshal: func(v interface{}) ([]byte, error) {
return msgpack.Marshal(v)
},
Unmarshal: func(b []byte, v interface{}) error {
return msgpack.Unmarshal(b, v)
},
}
})
return codec
}
使用编解码器实例设置密钥
package setter
import (
"github.com/Me/myapp/singleton"
"sync"
)
func Set(keys []string, vals []SomeObj, wg *sync.WaitGroup){
for i, k := range keys {
wg.Add(1)
// singleton is thread safe and could be used with goroutines
go func() {
codec := single.GetInstance()
codec.Set(&cache.Item{
Key: k,
Object: vals[i],
Expiration: time.Hour,
})
wg.Done()
}()
}
}
使用相同的编解码器实例获取对象
package getter
import (
"github.com/Me/myapp/singleton"
"sync"
)
func Set(keys []string, wg *sync.WaitGroup) chan SomeObj {
wanted_objs := make(chan *SomeObj)
for i, k := range keys {
wg.Add(1)
// singleton is thread safe and could be used with goroutines
go func() {
codec := singleton.GetInstance()
wanted := new(SomeObj)
if err := codec.Get(key, wanted); err == nil {
wanted_objs <- wanted
}
}()
}
return wanted_objs
}