dongxilan9351
2019-08-03 12:07
浏览 48

是否有任何自动增量机制使用Redigo包装器在Redis中存储键的值?

I'm new to go programming language and just wanted to write a small web app project with a good architecture.

I get some specific recangle objects through a post request.

type Rectangle struct {
X         int //starting x coordinate
Y         int //starting y coordinate
Width     int
Height    int
CreatedAt time.Time
}

I decided to choose redis for storing because it has high performance and I wanted to get my hands on that.

I have a bit confusion here :

  1. There is no specific key in the object's nature for storing, so I came up with the idea of auto incremention of keys but still stuck how to that because as I studied the pattern for insertion, it's something like:

    json, err := json.Marshal(rectangle)
    if err != nil {
        return err
    }
    
    _, err = connection.Do("SET", key, json)
    if err != nil {
        return err
    }
    

As you can see, I'm stuck what to write in the key field. I saw the Redis commands "INCR" but it seems none make sense for this pattern.

  1. If I want to get all rectangles regardless of their keys, will connection.Do("HGETALL", "*", rectangles[]) command help me get an array of all rectangles in the databse?

图片转代码服务由CSDN问答提供 功能建议

我刚接触编程语言,只是想编写一个具有良好体系结构的小型Web应用程序项目。

我通过发布请求获得了一些特定的矩形对象。

  type Rectangle struct {
X int //开始x坐标
Y  int //开始y坐标
宽度int 
高度int 
CreatedAt time.Time 
} 
   
 
 

我决定选择Redis进行存储,因为它具有高性能和 我想尝试一下。

我在这里有些困惑:

  1. 没有具体说明 关键在于存储对象的性质,所以我想到了自动增加关键的想法,但仍然坚持如何做到这一点,因为当我研究插入模式时,就像这样:

       json,err:= json.Marshal(rectangle)
    if err!= nil {
     return err 
    } 
     
    _,err = connection.Do(“ SET”,key,json)
    if err  != nil {
     return err 
    } 
        
      
     
     

    如您所见,我被卡住了 在关键字段。 我看到了Redis命令“ INCR”,但对于这种模式似乎没有任何意义。

    1. 如果我想获得所有矩形而不考虑其键 , connection.Do(“ HGETALL”,“ *”,rectangles [])命令是否可以帮助我获取数据库中所有矩形的数组?
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • drbe16008 2019-08-04 05:04
    已采纳

    A list meets the requirements set forth in the question.

    Add rectangle:

     _, err := c.Do("RPUSH", "rectangles", rectJSON). 
    

    Get all rectangles:

    rectJSONs, err := redis.ByteSlices(c.Do("LRANGE" "rectangles", 0, -1))
    if err != nil {
       // handle error
    }
    var rectangles []*Rectangle
    for _, rj := range rectJSONS {
       var r Rectangle
       if err := json.Unmarshal(rj, &r); err != nil {
           // handle error
       }
       rectangles = append(rectangles, &r)
    }
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题