在java中创建消息id

发布于 2024-08-23 11:57:12 字数 164 浏览 3 评论 0原文

我需要唯一标识我的应用程序中的消息。因此每条消息都应该包含它的 id。不过我有几个问题..

  1. 消息是否应该私下生成其 id 并且只为 id 提供 getter ?
  2. 创建 id 的最佳方法是什么? java中UUID类有什么替代品吗?

谢谢。

I need to uniquely identify messages in my app. Thus each message should contain its id. I have a couple of questions though..

  1. Should message generate its id privately and only provide getter for id?
  2. What is the best way to create ids? Any alternatives to UUID class in java?

Thanks.

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

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

发布评论

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

评论(2

兮颜 2024-08-30 11:57:12
  1. 显然,ID 不应该有公共设置器。让消息自行生成 ID 的另一种方法是将其传递到构造函数中。
  2. 如果您的应用程序是分布式的,那么除了 UUID 之外没有真正的替代品。如果未分发,AtomicIntegerAtomicLong 是很好的替代方案,可以同时使用而无需锁定。
  1. Obviously, the ID should not have a public setter. An alternative to having the message generate the ID itself is to pass it in the constructor.
  2. If your app is distributed, there is no real alternative to a UUID. If it's not distributed, AtomicInteger or AtomicLong are good alternatives that can be used concurrectly without locking.
暖风昔人 2024-08-30 11:57:12

如果没有更多上下文,我会回答:如果您关心速度,您总是可以有一个进程(在另一台机器上?)预先计算应用程序的 UUID。这样,应用程序就可以快速访问 UUID“池”。

  1. 人们不应该能够更改消息的 UID,否则还有什么意义?

  2. UUID 类有什么问题?如果是关于速度,那么请参见上面。

Without more context I would answer: if you are concerned about speed, you could always have a process (on an other machine?) pre-compute the UUIDs for the application. This way, the application could have quick access to a "pool" of UUIDs.

  1. One shouldn't be able to the change the UID of a message or else what is the point?

  2. What's wrong with UUID class ? if it is about speed, then see above.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文