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

从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.

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

报告相同问题?

悬赏问题

  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密
  • ¥15 关于#qt#的问题:我想实现qcustomplot完成坐标轴
  • ¥15 下列c语言代码为何输出了多余的空格