如何生成简短而独特的网址 [英] how to generate short, unique urls

查看:36
本文介绍了如何生成简短而独特的网址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我网站上的项目生成唯一的短网址.例如,用户可能添加了一个项目,结果 url 将类似于:

I am trying to generate unique, short urls for items on my site. For example, a user might add an item and the resulting url would be something like:

http://example.com/item/abc

我希望唯一标识符由 3 或 4 个字符组成,其中字符是字母和数字.我想不是随机生成字符串然后确保它们是唯一的并且尚未使用,而是可以提前生成它们并将它们存储在数据库中.然后当用户添加一个项目时,我可以从数据库中选择下一个缩短的 url 字符串并将其分配给该项目.这是解决这个问题的好方法吗?有更好的方法吗?我认为这会使其更简单,因为它们已经生成.但是,我也可以看到一个潜在的竞争问题,两个项目被分配了相同的识别字符串,我不确定 LOCK TABLES 是否是最好的解决方案.

I was hoping for the unique identifier to be made up of 3 or 4 characters, where the characters are letters and numbers. I thought instead of randomly generating the strings and then making sure they are unique and haven't been used yet, I could generate them all ahead of time and store them in a database. Then when a user adds an item I could just select the next shortened url string from the database and assign it to that item. Is this a good way to solve this? Are there better ways? I thought it would make it simpler since they are already generated. However, I could also see a potential race issue with two items being assigned the same identifying string, and I'm not sure if LOCK TABLES would be the best solution or not.

另外,如果不使用 LOCK TABLES,这样的事情能保证 MySQL 中没有竞争条件吗?

Also, without using LOCK TABLES, could something like this guarantee no race conditions in MySQL?

update ids set item_id=1 WHERE id=(SELECT id FROM ids WHERE item_id IS NULL LIMIT 1);

然后我可以为 id 为 1 的项目选择 id?在该查询期间,没有其他查询能够声明它吗?

And then I could select the id for item that has id 1? During that query would no other query be able to claim it?

推荐答案

对于后来发现这个问题的任何人,我按照@Swapnil 建议的链接中建议的流程进行操作:

For anyone who finds this question later, I followed the process suggested in the link that @Swapnil suggested:

如何编写网址缩短程序?

那里列出了各种语言的一些实现,但我使用的是 perl 并且没有在那里列出,而且我似乎找不到其他地方已经存在的 perl.因此,如果将来对任何人有帮助,我编写了这个 perl 模块来帮助缩短 url:

There were some implementations listed there for various languages, but I am using perl and that wasn't listed there and I couldn't seem to find a perl one that already existed elsewhere. So if it helps anyone in the future, I wrote this perl module to help with url shortening:

Short::URL

感谢@Swapnil 将我指向正确的地方.

Thanks to @Swapnil for pointing me to the right place.

这篇关于如何生成简短而独特的网址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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