Redis as unique atomic id generator - Thread safe way for web app to avoid race condition

痴心易碎 提交于 2019-12-22 16:07:09

问题


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?


回答1:


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).



来源:https://stackoverflow.com/questions/24028171/redis-as-unique-atomic-id-generator-thread-safe-way-for-web-app-to-avoid-race

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!