Sequence Generator in Java for Unique Id

后端 未结 3 1984
面向向阳花
面向向阳花 2020-12-19 01:59

I am planning to write a sequence generator which will be used in my REST resource implementation class during post to generate unique id. Since every post request is handl

3条回答
  •  一整个雨季
    2020-12-19 02:46

    If you are open to using String for IDs, instead of int, you might want to look into using UUID (Universally Unique Identifier). Very easy to use and as the name implies, they are unique. Here is an example of how to generate one:

    // the value of uuid will be something like '03c9a439-fba6-41e1-a18a-4c542c12e6a8'
    String uuid = java.util.UUID.randomUUID().toString()
    

    A UUID also provides better security than int because with integers you can guess the next request ID by simply adding 1 to your request ID, but UUIDs are not sequential and chances of anyone guessing anyone else's request ID are pretty slim.

提交回复
热议问题