douou9786 2016-12-29 23:42
浏览 99
已采纳

在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 02: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
    }
    

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部