Web 服务返回唯一的自动递增人类可读 ID 号

发布于 2024-08-25 16:08:34 字数 252 浏览 1 评论 0原文

我正在创建一个简单的 Web 服务,当轮询时返回一个唯一的 id。 ID 必须是人类可读的(即不是 guid,可能采用 000023 的形式),并且每次调用时都会简单地加 1。

现在我需要考虑它可能被两个不同的应用程序同时调用,并且我不希望它向每个应用程序返回相同的数字。

除了使用数据库来存储当前号码之外,还有其他选择吗?

当然,这之前已经做过了,如果有的话,任何人都可以给我指出一些源代码吗?

谢谢,

尼尔

I'm looking to create a simple web service that when polled returns a unique id. The ID has to be human readable (i.e. not a guid, probably in the form 000023) and is simply incremented by 1 each time its called.

Now I need to consider that it may be called by two different applications at the same time and I don't want it to return the same number to each application.

Is there another option than using a database to store the current number?

Surely this has been done before, can anyone point me at some source code if it is.

Thanks,

Neil

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

玩物 2024-09-01 16:08:34

使用关键部分代码片段一次控制一段代码中的流程。您可以使用锁定 语句或者稍微更硬核并直接使用互斥体。这样做将确保您向每个呼叫者返回不同的号码。

至于存储它,使用数据库返回自动递增数字有点过分 - 尽管 SQLServer 和 Oracle(很可能还有其他数据库,但我不能代表它们)都提供自动递增键功能,因此您可以将 Web 服务称为,在数据库表中生成一个新条目,返回密钥,调用者可以使用该数字作为返回该记录的密钥(如果您在初始调用后稍后保存更多数据)。这样,您还可以让数据库担心唯一编号的生成,而不必担心它的细节 - 尽管如果您还没有数据库,这不是一个好的选择。

另一种选择是将其存储在本地文件中,尽管读取文件、增加数字并将其写回的成本很高,所有这些都在关键部分内。

Use a critical section piece of code to control flow one at a time through a section of code. You can do this using the lock statement or by being slightly more hardcore and using a mutex directly. Doing this will ensure that you return a different number to each caller.

As for storing it, using a database is overkill for returning an auto incrementing number - although SQLServer and Oracle (and most likely others but i can't speak for them) both provide an auto incrementing keys feature, so you could have the webservice called, generate a new entry in the database table, return the key, and the caller can use that number as a key back to that record (if you are saving more data later after the initial call). This way you also let the database worry about the generation of unique numbers, you don't have to worry about the details of it - although this is not a good option if you don't already have a database.

The other option is to store it in a local file, although that would be expensive to read the file, increment the number, and write it back out, all within a critical section.

睫毛上残留的泪 2024-09-01 16:08:34

你可以使用一个文件。

伪代码:

if (!locked('counter.txt'))
   counter = read('counter.txt')
else
   wait
   startAgain
lock('counter.txt')
counter++
print counter
write('counter.txt', counter)
unlock('counter.txt)

you can use a file.

Pseudocode:

if (!locked('counter.txt'))
   counter = read('counter.txt')
else
   wait
   startAgain
lock('counter.txt')
counter++
print counter
write('counter.txt', counter)
unlock('counter.txt)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文