PHP原生随机字符串生成与问题
针对需要生成固定长度随机字符串的需求,
先展示一段PHP实现代码。
$str_md5=md5(uniqid());
$rand = mt_rand(1, 28);
$str1=substr($str_md5,$rand,6);
$rand = mt_rand(1, 28);
$str2=substr($str_md5,$rand,6);
$rand = mt_rand(1, 28);
$str3=substr($str_md5,$rand,6);
$code=substr($str1.$str2.$str3,0,8);

生成180000个随机字符串后,按重复数量倒序排列可见,结果中基本都存在重复项,但整体表现尚可。
为提升C语言能力,尝试使用C语言重新实现随机字符串生成逻辑。
实现过程中调用了随机数函数srand()和rand()。
经过一两个小时的调试,发现随机数仍存在缺陷。在高并发访问场景下,系统时间几乎同步,导致srand提供的种子时间被视为相同,进而产生相同的随机数和一模一样的随机字符串,循环输出时几乎无差异。
随后想到利用ukey扩展获取唯一ID,若每次访问都产生唯一ID,将其作为种子时间是否可行?实验证明该方案有效。

上图展示了生成的随机字符串,支持自定义长度,也可仅输出数字串。相比PHP版本,该方法生成的随机字符串重复率更低,且执行速度更快。
PHP_FUNCTION(get_random__num_str)
{
int length=8;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &length) == FAILURE)
{
length=8;
}
length++;
int flag, i;
char* string;
__uint64_t timestamp = realtime();
__uint64_t retval;
int len;
char buf[128];
if (timestamp == 0ULL) {
RETURN_FALSE;
}
spin_lock(lock, pid);
if (context->last_timestamp == timestamp) {
context->sequence = (context->sequence + 1) & context->sequence_mask;
if (context->sequence == 0) {
timestamp = skip_next_millis();
}
} else {
context->sequence = 0; /* Back to zero */
}
context->last_timestamp = timestamp;
retval = ((timestamp - context->twepoch) << context->timestamp_left_shift)
| (context->datacenter_id << context->datacenter_id_shift)
| (worker_id << context->worker_id_shift)
| context->sequence;
spin_unlock(lock, pid);
//printf('%ld',retval);
srand((unsigned)retval);
//srand((unsigned) time(NULL ));
if ((string = (char*) emalloc(length)) == NULL )
{
//myLog("Malloc failed!flag:14\n");
RETURN_NULL() ;
}
for (i = 0; i < length - 1; i++)
{
flag = rand() % 3;
switch (flag)
{
case 0:
string[i] = '1' + rand() % 5;
break;
case 1:
string[i] = '2' + rand() % 7;
break;
case 2:
string[i] = '0' + rand() % 10;
break;
default:
string[i] = '9';
break;
}
}
string[length - 1] = '\0';
RETURN_STRINGL(string,length,0);
}
PHP_FUNCTION(get_random_str)
{
int length=8;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &length) == FAILURE)
{
length=8;
}
length++;
int flag, i;
char* string;
__uint64_t timestamp = realtime();
__uint64_t retval;
int len;
char buf[128];
if (timestamp == 0ULL) {
RETURN_FALSE;
}
spin_lock(lock, pid);
if (context->last_timestamp == timestamp) {
context->sequence = (context->sequence + 1) & context->sequence_mask;
if (context->sequence == 0) {
timestamp = skip_next_millis();
}
} else {
context->sequence = 0; /* Back to zero */
}
context->last_timestamp = timestamp;
retval = ((timestamp - context->twepoch) << context->timestamp_left_shift)
| (context->datacenter_id << context->datacenter_id_shift)
| (worker_id << context->worker_id_shift)
| context->sequence;
spin_unlock(lock, pid);
//printf('%ld',retval);
srand((unsigned)retval);
//srand((unsigned) time(NULL ));
if ((string = (char*) emalloc(length)) == NULL )
{
//myLog("Malloc failed!flag:14\n");
RETURN_NULL() ;
}
for (i = 0; i < length - 1; i++)
{
flag = rand() % 3;
switch (flag)
{
case 0:
string[i] = 'A' + rand() % 26;
break;
case 1:
string[i] = 'a' + rand() % 26;
break;
case 2:
string[i] = '0' + rand() % 10;
break;
default:
string[i] = 'x';
break;
}
}
string[length - 1] = '\0';
RETURN_STRINGL(string,length,0);
}

上图记录了PHP生成18万个随机字符串所消耗的时间。

上图记录了C扩展生成18万个随机字符串所消耗的时间。
测试环境均为配备1G内存、双核处理器的阿里云服务器。
只需在ukey扩展中加入相关代码,即可生产随机字符串及指定长度的数字字符串。此处使用的是PHP唯一ID生成扩展ukey。
php.ini中的配置项如下:
[ukey]
ukey.datacenter = integer
ukey.worker = integer
ukey.twepoch = uint64
datacenter配置项为整数,用于设置数据中心; worker配置项为整数,用于设置数据中心的机器序号; twepoch配置项为64位整数,用于设置时间戳基数,该值越大,生成的ID越小;
安装步骤如下:
$ cd ./ukey
$ phpize
$ ./configure
$ make
$ sudo make install
Ukey提供了3个实用函数:
ukey_next_id() -- 用于生成唯一ID ukey_to_timestamp(ID) -- 用于将ID转换为时间戳 ukey_to_machine(ID) -- 用于将ID转换为机器信息
使用实例如下:
<?php
$id = ukey_next_id();
echo $id;
$timestamp = ukey_to_timestamp($id);
echo date('Y-m-d H:i:s', $timestamp);
$info = ukey_to_machine($id)
var_dump($info);
?>
以上即为本文的全部内容,希望能为读者的学习提供帮助。