java Web应用程序中的唯一序列号 [英] Unique serial number in a java web application

查看:910
本文介绍了java Web应用程序中的唯一序列号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直想知道生成独特ID的正确做法是什么?事情是在我的网络应用程序中我将有一个插件系统,当用户注册一个插件我想为它生成一个唯一的序列ID。我一直在考虑将所有数字存储在数据库或服务器上的文件中,生成一个随机数并检查它是否已存在于数据库/文件中,但这似乎不太好。还有其他方法吗?使用UUID是首选方式吗?

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?

推荐答案

如果id是面向用户的,它们看起来是,然后你想让它们难以猜测。使用内置的 UUID 课程,该课程为您生成随机ID可以为你很好地格式化它们。提取:

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

示例输出:

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.

另一种有趣的方法是 MongoDB 使用,但这可能是你的需求过度:

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


BSON ObjectID是一个12字节的值
,包含一个4字节的时间戳
(自纪元以来的秒数),一个3字节的
机器ID,一个2 -byte进程id和
3字节计数器。请注意,
时间戳和计数器字段必须是
存储大端,不像其他
BSON

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

如果他们不是面向用户,那么你可以将它留给数据库来做一个自动递增的id:1,2,3等等。

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.

这篇关于java Web应用程序中的唯一序列号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆