douou9786 2016-12-30 07: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 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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题