How to generate unique ids for my scaled Servers w

2019-04-12 08:43发布

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

标签: php scale
5条回答
ゆ 、 Hurt°
2楼-- · 2019-04-12 09:23

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.

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-04-12 09:27

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).

查看更多
Melony?
4楼-- · 2019-04-12 09:28

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

查看更多
叛逆
5楼-- · 2019-04-12 09:33

Try

$uid = uniqid($serverId, true);

This will prefix every $uid with the $serverId.

查看更多
贪生不怕死
6楼-- · 2019-04-12 09:34

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).

查看更多
登录 后发表回答