如何在共享数据库上同时生成唯一的用户名?
我需要自动生成帐户名。它们将在访问我的服务的用户软件中使用,因此它们不一定很漂亮。我想任何足够长的字母数字字符串都可以。假设我已经有了一个可以生成足够好的字母数字字符串的算法。
有两个主要要求:它们必须是唯一的并且将同时生成。具体来说,我的服务将在多台计算机上运行,并且所有副本都将访问相同的共享数据库。我需要以这样的方式生成这些用户名,即没有两个节点生成相同的用户名。
我该怎么做?我是否就放弃这个想法并使用 GUID?对于这种情况,是否有更漂亮的 GUID 方式?
I need to generate account names automatically. They will be used in user software that will access my service, so they are not necessarily pretty looking. I guess any alphanumeric string long enough will do. Assume I already have an algorithm that produces good enough alphanumeric string.
There're two major requirements: they must be unique and they will be generated concurrently. Specifically my service will run on multiple machines and all copies will access the same shared database. I need to generate those usernames in such way that no two nodes ever generate identical usernames.
How do I do this? Do I just leave this idea and use GUIDs? Is there a prettier way that GUIDs for this scenario?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
其中之一:
如果在多个节点上使用 SQL Server 复制(编辑:之前想太多)
所有这些都是并发安全的
One of:
If SQL Server replication is used over multiple nodes (Edit: was thinking too much before)
All are concurrency safe
示例输出:
如果您想测试此代码的并发问题,您可以运行
UPDATE ...; GO 100000
和更新...; GO 100
在 SSMS 中的两个单独的窗口/查询中,最后,您可以运行此查询SELECT UserName, COUNT(*) Num FROM dbo.[User] ORDER BY COUNT(*) DESC< /code> 看看是否可以找到重复项。
Sample output:
If you want to test this code for concurrency issues you can run
UPDATE ...; GO 100000
andUPDATE ...; GO 100
in SSMS in two separated windows/queries and, at the end, you can run this querySELECT UserName, COUNT(*) Num FROM dbo.[User] ORDER BY COUNT(*) DESC
to see if you can find duplicates.