Best way to create bullet-proof counter
I am building a gaming system where many players can play some sort of table game together. There could be hundreds of game tables at the same time. The system consists of several components where the main components are gaming servers and DBworker and in between there is rabbitMQ. DBWorker is the component that takes care of the databases.
So, I need to make sure that each game has unique ID to properly track results of the games. I would love to have some sort of auto-increment solution. Of course I can do some sort of sequence in PostgreSQL DB and pull new ID every time but for me it seems as an obvious bottleneck (I don't want开发者_StackOverflow中文版 to be linked to DB all the time. In case DB goes down show must go on while our engineers recover DB).
So, any ideas or personal experience of implementing something similar?
p.s. I am thinking about timestamp as ID but real ID would be better. Am not sure why I think this - if I am wrong, please correct me.
Thank in advance to everyone!
Is that a requirement than the ID is an integer? If not, then why not just use UUIDs (RFC 4122)? Random UUID should be good enough for your purpose, I guess.
- You need to make sure all game ID's are created in just one place - some sort of "Factory".
- Given an initial value (the last know / recorded ID) the factory generates the next logical one - a plain old incrementing int would be fine).
- If the factory is in memory (along with the rest of your logic) it should have no problem managing the generation of unique IDs. Having it work at runtime, in memory as just another part of the app means you aren't going back to the DB everytime.
- At some point data (including the ID will be persisted - this is where the "last known ID" will come from next time you start up. The only risk is ensuring that you never completely fail to save that ID before the factory needs it again.
I did a similar thing with a simple desktop app I built for personal use, whenever I save an object the app you generate a new unique ID - which was a simple int based off the last value (+1). At certain points in the life-cycle of the running app I save the state to disk (serialized XML). The only time this will fail is if I can't open the previously saved XML on start-up, which is when the app get's the starting value to increment off.
I don't know if it's bullet-proof or "the best" but it worked well for what I needed.
精彩评论