logid生成

lighttpd中的logid由mod_logid生成,mod_logid的工作原理在于, 收到请求后, 根据当前ip, pid, time stamp, counter 计算出唯一的logid值 (24位的字符串组成) ,然后将该字符串做为输入的header。该24位的字符串可以保证为全局唯一。

一种实现方式如下:

typedefunsigned long long logid_t;

typedef unsigned long long spanid_t;

/*

* logid compents of twoparts

*/

typedef struct __logid_generator_s{

uint64_t logid_high;

uint64_tlogid_low;

}logid_generator_t;

int generator_init(logid_generator_t*generator){

int32_t len = 0;

uint32_t sign[2] = {0};

char buffer[1024] = {0};

time_t now = time(NULL);//当前时间戳

pid_t pid = getpid();//当前进程ID

memset(generator, 0,sizeof(logid_generator_t));

if(gethostname(buffer,sizeof(buffer) - sizeof(now)) != 0){// 当前机器IP

return INIT_FAILED;

}

len = strlen(buffer);

memcpy(buffer + len,&now, sizeof(now));

len += sizeof(now);

len += snprintf(buffer + len,sizeof(buffer) - len, "%d", pid);

creat_sign_fs64(buffer, len, &sign[0], &sign[1]);// 计算hash

generator->logid_high =(((uint64_t)(sign[0] + sign[1]))) << 40;// 构建24位数字作为高位

generator->logid_low =0;

return INIT_SUCCESS;

}

logid_t generate_logid(logid_generator_t*generator){

generator->logid_low =(generator->logid_low++)&((uint64_t)0x000000ffffffffff);//低位数字作为counter

return (generator->logid_high +generator->logid_low);

}

你可能感兴趣的:(logid生成)