问题
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
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.
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);
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?
回答1:
For anyone who finds this question later, I followed the process suggested in the link that @Swapnil suggested:
How to code a URL shortener?
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
Thanks to @Swapnil for pointing me to the right place.
回答2:
Just about your short urls question.
You can encode the url in a shorten representation.
In python you can hash the url and later encode it to b64, that will reduce the length and have a unique representation for the url
>>> import base64
>>> import md5
>>> url = '/item/abc'
>>> hash = md5.new(url).digest()[-4:] # get the hash for the url
>>> hash = _hash.replace('=','').replace('/','_') # some cleaning
>>> print base64.b64encode(hash)
'CVKi2Q'
来源:https://stackoverflow.com/questions/24975380/how-to-generate-short-unique-urls