dongqiang8474 2018-08-28 00:14
浏览 673
已采纳

从Redis / Golang客户端读取全部数据

I have a Redis deployment acting as a caching layer. The cache is not very big and we would like to read all the items (key/values) at once from our Golang program. The only solution I found is to iterate through all master servers (it is a Redis cluster), execute a Scan to get all the keys and then iterate the keys to get the values.

err := cch.client.ForEachMaster(func(cl *redis.Client) error {
    wg.Add(1)
    defer wg.Done()
    var cursor uint64
    var n int
    numFor := 0
    for {

        var keys []string
        var err error
        keys, cursor, err = cl.Scan(cursor, "*", 10).Result()
        if err != nil {
            panic(err)
        }
        n += len(keys)

        for _, keyval := range keys {
            var cont Content
            if err := cch.items.Get(keyval, &cont); err == nil {

            } else {
                log.Warnf("Error getting Key %s from cache: %s from master %s", keyval, err)
            }
        }

        if cursor == 0 {
            break
        }
    }
    return nil
})
wg.Wait()

Is there a better way to do this? Cannot believe I need so many roundtrips to Redis to get the values. Thanks!

  • 写回答

1条回答 默认 最新

  • douningle7944 2018-08-28 06:15
    关注

    1) You can use KEYS command to get all the keys and then access every key. But that is not a recommended way in some cases since KEYS upon a big set of cache will cause long-blocking in Redis server. But if you just have a tiny cache, KEYS is simple and elegant command you can use.

    2) You can also push the relevant keys into a hash using HSET command. So you can use HGETALL to get those key-values at once. This way can help your cache to become good-looking.

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

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)