大家好,有没有人试过把redis散列存储为proto编组和unmarshall,并在struct中检索?我在这方面正面临问题。在下面做但不能得到预期的结果
定义interface
注意:使用来自redis.NewClusterClient的github.com/go-redis/redis/v8
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) 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()
style := style_fetch.Style{}
err := proto.Unmarshal(b, &style)
if err != nil {
return nil, err
}
productRedis := &style_fetch.CMSStyleRedisEntry{Style: &style}
return productRedis, nil```发布于 2022-11-11 01:00:23
解析
在独立字段级别上,而不是在整个结构上,需要原始属性,就像这里我们所做的hset/hmset单个字段一样。
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
}https://stackoverflow.com/questions/74388101
复制相似问题