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?
  • 写回答

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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。