如何创建URL缩短器?

£可爱£侵袭症+ 提交于 2020-05-06 18:51:55

问题:

I want to create a URL shortener service where you can write a long URL into an input field and the service shortens the URL to " http://www.example.org/abcdef ". 我想创建一个URL缩短服务,您可以在其中将长URL写入输入字段,然后该服务将URL缩短为“ http://www.example.org/abcdef ”。

Instead of " abcdef " there can be any other string with six characters containing az, AZ and 0-9 . 除了“ abcdef ”之外,还可以有其他任何六个字符串,包含az, AZ and 0-9 That makes 56~57 billion possible strings. 这使得56〜570亿个可能的字符串。

My approach: 我的方法:

I have a database table with three columns: 我有一个包含三列的数据库表:

  1. id, integer, auto-increment id,整数,自动递增
  2. long, string, the long URL the user entered long,字符串,用户输入的长URL
  3. short, string, the shortened URL (or just the six characters) 简短的字符串,缩短的URL(或仅六个字符)

I would then insert the long URL into the table. 然后,我将长网址插入表中。 Then I would select the auto-increment value for " id " and build a hash of it. 然后,我将为“ id ”选择自动增量值,并为其构建一个哈希值。 This hash should then be inserted as " short ". 然后应将此散列插入为“ short ”。 But what sort of hash should I build? 但是我应该建立什么样的哈希? Hash algorithms like MD5 create too long strings. 像MD5这样的哈希算法创建的字符串太长。 I don't use these algorithms, I think. 我认为我不使用这些算法。 A self-built algorithm will work, too. 自建算法也将起作用。

My idea: 我的点子:

For " http://www.google.de/ " I get the auto-increment id 239472 . 对于“ http://www.google.de/ ”,我得到了自动增量ID 239472 Then I do the following steps: 然后,我执行以下步骤:

short = '';
if divisible by 2, add "a"+the result to short
if divisible by 3, add "b"+the result to short
... until I have divisors for a-z and A-Z.

That could be repeated until the number isn't divisible any more. 可以重复进行直到该数字不再可除。 Do you think this is a good approach? 您认为这是个好方法吗? Do you have a better idea? 你有更好的主意吗?

Due to the ongoing interest in this topic, I've published an efficient solution to GitHub , with implementations for JavaScript , PHP , Python and Java . 由于对该主题的持续关注,我为GitHub发布了一种有效的解决方案 ,其中包含JavaScriptPHPPythonJava的实现 Add your solutions if you like :) 如果您愿意,请添加您的解决方案:)


解决方案:

参考一: https://stackoom.com/question/371x/如何创建URL缩短器
参考二: https://oldbug.net/q/371x/How-do-I-create-a-URL-shortener
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!