首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >go-redis HGETALL原始信息

go-redis HGETALL原始信息
EN

Stack Overflow用户
提问于 2022-11-10 11:16:26
回答 1查看 38关注 0票数 1

大家好,有没有人试过把redis散列存储为proto编组和unmarshall,并在struct中检索?我在这方面正面临问题。在下面做但不能得到预期的结果

定义interface

  • Execution HGETALL并试图在interface

  • converting to字节数组

  • 中获得结果的
  1. 将其解析为所需的struct

注意:使用来自redis.NewClusterClientgithub.com/go-redis/redis/v8

代码语言:javascript
复制
    var res interface{}
    res, err = redis.GoRedisInstance().Do(context.Background(), "HGETALL", key).Result()
    if err != nil {
    return nil, false, err
    }
    if response, ok := res.(string); ok {
    value = []byte(response)
    }
    styleEntry, err := parseStyle(ctx, value)
代码语言:javascript
复制
    func parseStyle(ctx context.Context, b []byte) (*style_fetch.CMSStyleRedisEntry, error) {
    // convert to product redis object
    productRedis := style_fetch.CMSStyleRedisEntry{}
    err := proto.Unmarshal(b, &productRedis)
    if err != nil {
    return nil, err
    }
    return &productRedis, nil
    }

在调试redis.GoRedisInstance().Do(context.Background(), "HGETALL", key)时,我看到了interface{}([]interface{})键- interface{}(string)值(已封送)- interface{}(string)附加快照,但是.Result为两者提供了(不可读、无法解析接口类型)。

它适用于HGET通过res, err = redis.GoRedisInstance().Do(context.Background(), "HGET", key, "style").Result()

代码语言:javascript
复制
style := style_fetch.Style{}
    err := proto.Unmarshal(b, &style)
    if err != nil {
        return nil, err
    }
    productRedis := &style_fetch.CMSStyleRedisEntry{Style: &style}
    return productRedis, nil```
EN

回答 1

Stack Overflow用户

发布于 2022-11-11 01:00:23

解析

在独立字段级别上,而不是在整个结构上,需要原始属性,就像这里我们所做的hset/hmset单个字段一样。

代码语言:javascript
复制
unboxed, ok := res.(map[string]string)
if !ok {
    fmt.Println("Output should be a pointer of a map")
}
//If error is nil but value is also empty/nil. Data not found in redis, reindex
if unboxed == nil || len(unboxed) <= 0 {
    //async reindexing call
    isCacheMiss = true
    statsd.Instance().Incr("redis.keyNotPresentError", 1)
    return nil, isCacheMiss, nil
}

redisEntry := &style_fetch.CMSStyleRedisEntry{}
for key, value := range unboxed {
    if key == "style" {
        style := &style_fetch.Style{}
        proto.Unmarshal([]byte(value), style)
        redisEntry.Style = style
    } 
           //...other keys
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74388101

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档