Yes, you can access the same map by using a common Codec
instance for both packages and both of set and get operations. For this purposes you need to implement a singleton instance producer. Desirably it should be a thread safe implementation. In this way you will save a lot of resource and guarantee connection correctness. This is significant to keep a client the only to prevent bugs and save resource.
Client is a Redis client representing a pool of zero or more underlying connections. It's safe for concurrent use by multiple goroutines.
Singleton codec
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
}
Set key using codec instance
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()
}()
}
}
Get object using the same codec instance
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
}