douou9786
2016-12-30 07:42
浏览 91

在Golang中的不同包中获取Redis变量

I'm using go-redis/redis and go-redis/cache to cache Go objects.

import (
    "communication/MQ_pkg"

    "gopkg.in/go-redis/cache.v3"
    "gopkg.in/vmihailenco/msgpack.v2"
)

obj := &VAR_STRUCT{}        

Codec.Set(&cache.Item{
            Key:    key,
            Object: obj,
        })

where obj is an structure having go maps(key value pair) By Using above code i am setting a key and saving values into it. This is in package common. Now i want to access this in different package say GetRedis_pkg without importing pkg. Is there are any way i can do that. And can i access particular map inside that that structure by any means using redis key imorted gopkg.in/go-redis/cache.v3 to use redis in my code

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doudaochu1699 2016-12-30 10:08
    已采纳

    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
    }
    
    点赞 打赏 评论

相关推荐 更多相似问题