K
K
Kagtaviy2016-05-04 20:17:26
NoSQL
Kagtaviy, 2016-05-04 20:17:26

How to use autoincrement properly?

Hello, I can't figure out how to use incr correctly in redis.
I need to create a post, each post has a unique id, title, description.
When creating a new post, you need to assign a unique id, I understand that this is done through incr, but I can’t figure out how to put it into practice correctly?
Thanks in advance.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
U
uvelichitel, 2016-05-04
@Kagtaviy

INCR can be done on the redis side (assuming https://github.com/garyburd/redigo client as the most popular one)

conn, err := redis.DialURL(YourRedisUrl, yourOptions)
var ID int64
ID=redis.Int64(conn.Do("INCR", "IDcounter"))
or on the Go server side
then something like
_, err := conn.Do("HMSET", redis.Args{}.Add(ID).AddFlat(&NewPost)...)
You have not described how NewPost will be represented on the Go side and on the redis side, so struct and hash are assumed, respectively. The ID is implemented simply as a redis key, not a record field, making indexing and searching easier. The whole point of dancing with INCR (or sync.atomic.AddInt64() on the Go side) is to achieve security and consistency when multiple goroutines are accessed concurrently. If you create posts in only one thread, then ID++it is enough.

I
Iron Bug, 2016-05-04
@rare

do you use radish as your main storage? do not do it this way. it is better to create a new post in the database and cache it in the radish, the subd will generate a new id for you (do you want auto-increment?). And incr is needed for something else, for example, to atomically increase the value of a frequently changing counter.
UPD: If you still want to use radish as the main storage, create a last_id key in it and assign id = incr(last_id) to each new post

A
Andrey Burov, 2015-06-08
@BuriK666

$('html, body')
Scroll only on body. html and so scrollTop has 0

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question