I plan to use redis as an unique atomic id generator. However, my concern there might be simulatoneous web requests from multiple browsers. I was wondering, what is the common practice to make the following operations atomic?
get id from redis
if id is not found
insert id as 0 into redis
else
store the id in a variable
increase id by one
store the new id back to redis
If I were in desktop app or mobile app, I would use synchronized
keyword in Java to avoid race condition.
However, how about for a PHP web app?
Assuming you're looking to generate sequential ids, you can use Redis and the INCR command without worrying about race conditions. Since Redis is (mostly) single threaded, you are assured that every request will get it's own unique id from it.
Furthermore, you don't need to check the id key's existence/initialize it because Redis will do that for you (i.e. if you INCR a non-existent key, it will be first created and set to 0 automatically).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With