Unique serial number in a java web application

I've been wondering what's the correct practice for generating unique ids? The thing is in my web app I'll have a plugin system, when a user registers a plugin I want to generate a unique serial ID for it. I've been thinking about storing all numbers in a DB or a file on the server, generating a random number and checking whether it already exists in the DB/file, but that doesn't seem that good. Are there other ways to do it? Would using the UUID be the preferred way to go?


If the ids are user-facing, which it seems they are, then you want them to be difficult to guess. Use the built-in UUID class, which generates random ids for you and can format them nicely for you. Extract:

UUID idOne = UUID.randomUUID();
UUID idTwo = UUID.randomUUID();
log("UUID One: " + idOne);
log("UUID Two: " + idTwo);

Example output:

UUID One: 067e6162-3b6f-4ae2-a171-2470b63dff00 
UUID Two: 54947df8-0e9e-4471-a2f9-9af509fb5889

There are other solutions in the link provided. I think it compares the methods quite well, so choose the one which best suits your needs.

Another interesting method is the one MongoDB uses, but this is possibly overkill for your needs:

A BSON ObjectID is a 12-byte value consisting of a 4-byte timestamp (seconds since epoch), a 3-byte machine id, a 2-byte process id, and a 3-byte counter. Note that the timestamp and counter fields must be stored big endian unlike the rest of BSON

If they weren't user facing, then you could just leave it to the database to do an auto-incrementing id: 1, 2, 3, etc.


为什么不去找一个静态的(或者,在这种情况下是一个上下文范围的)AtomicInteger,当一个插件被注册时会增加?


You could base it on user ID and timestamp, ensuring uniqueness but also providing a certain "readability"? Eg User ID = 101, timestamp = 23 Dec 2010 13:54, you could give it ID:

201012231354101

or

101201012231354

The alternative UUID is obviously guaranteed to be unique but takes up a lot of DB space, and is quite unwieldy to work with.

A final idea is to ask your central DB for a unique ID, eg Oracle has sequences, or MySQL uses AUTO_INCREMENT fields, to assign unique integers.

链接地址: http://www.djcxy.com/p/91480.html

上一篇: SecureRandom.uuid与UUID宝石

下一篇: Java Web应用程序中的唯一序列号