由于要用到固定长度的随机字符串。
首先是一段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);
上图是产生的随机字符串,可以自定义长度。也同样可以输出只有数字的字符串。相较PHP所产生的随机字符串重复率更低且速度更快。
PHP_FUNCTION(get_random__num_str){ int length=8; if (zend_<p style="color:transparent">。本文来源gao!%daima.com搞$代*!码网1</p><cite>搞代gaodaima码</cite>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) <timestamp_left_shift) | (context->datacenter_id <datacenter_id_shift) | (worker_id <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 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) <timestamp_left_shift) | (context->datacenter_id <datacenter_id_shift) | (worker_id <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);}
上图是C扩展生成18W随机字符串所用的时间
所用的服务器都是1G内存 双核的阿里云服务器。
只要在ukey中加入上如代码就可以生产随机字符串和随机长度数字字符串,PHP唯一ID生成扩展ukey。
php.ini的配置项:
[ukey]ukey.datacenter = integerukey.worker = integerukey.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转换成机器信息
使用实例:
以上就是本文的全部内容,希望对大家的学习有所帮助。