How to generate unique ids for my scaled Servers with PHP?

ぐ巨炮叔叔 提交于 2019-12-21 20:48:03

问题


I'm using the PHP function uniqid() on my server. It should be something like a microtime. So I think it is unique FOR ONE server. Is it correct?

How can I get a unique id if I scale my server with a loadbalancer? I need a string with less than 31 characters.

Thanks


回答1:


I would suggest combining multiple sources of entropy. This way you wouldn't rely on some assumptions (local IP address being different) or luck (two servers won't do the same thing exactly at the same nanotime).

Things that come to my mind (and are pretty portable, not platform specific):

  • nanotime,
  • open temp directory in file system and count the file sizes there,
  • current script's file system datetime stamps,
  • run a simple no-op loop and count its duration,
  • ...

After all you can use this as an input to some hash function, just to normalize to 30-byte string (e.g. last 30 bytes of md5sum of concatenation of strval() of input values).




回答2:


You can use uniqid() with a different prefix for each server passed as first argument. Check the documentation.

string uniqid ([ string $prefix = "" [, bool $more_entropy = false ]] )

prefix
Can be useful, for instance, if you generate identifiers simultaneously on several hosts that might happen to generate the identifier at the same microsecond.
With an empty prefix, the returned string will be 13 characters long. If more_entropy is TRUE, it will be 23 characters.

Example:

$serverId = str_replace('.', '', $_SERVER["SERVER_ADDR"].$_SERVER["SERVER_PORT"]);
$uid      = substr(uniqid($serverId, true), 0, 30);

Or check out this great uuid() function: http://cakebaker.42dh.com/wp-content/uploads/2007/01/uuid_component_2007-01-24.zip




回答3:


Yes, as its manual page says, it's based on the current time in microseconds.

You can use the prefix argument to pass in a host-specific prefix.

Even with the more_entropy argument you have 7 characters left for the prefix, allowing for 256**7 hosts.




回答4:


You should set the prefix to a unique string (unique for each server is your system). Examples could be hostname or IP address. Keep this to less than 17 characters (or 7 if you use additional entropy).




回答5:


Try

$uid = uniqid($serverId, true);

This will prefix every $uid with the $serverId.



来源:https://stackoverflow.com/questions/5088922/how-to-generate-unique-ids-for-my-scaled-servers-with-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!