This commit is contained in:
aozhiwei 2018-10-16 11:57:00 +08:00
parent cefcdd78b0
commit 24f2912dbf
3 changed files with 36 additions and 13 deletions

View File

@ -10,14 +10,20 @@ namespace a8
namespace uuid
{
long long SnowFlake::FetchTime(long long value)
{
return (value >> 22) + a8::uuid::A8_EPOCH;
}
int SnowFlake::FetchMachineId(long long value)
{
long long machineid = (value >> 12) & (1023);
long long machineid = (value >> SEQUNCE_ID_BIT_NUM) & (MAX_MACHINE_ID);
return machineid;
}
SnowFlake::SnowFlake()
int SnowFlake::FetchSequnceId(long long value)
{
return value & MAX_SEQUNCE_ID;
}
long long SnowFlake::Generate()
@ -26,7 +32,7 @@ namespace a8
long long time = a8::GetMilliSecond();
if (time == last_generate_tick) {//同一微妙内
sequence_id++;
if (sequence_id >= 0x1000) { //计数已经用完
if (sequence_id >= MAX_SEQUNCE_ID) { //计数已经用完
while (time <= last_generate_tick) {
::usleep(1);
time = a8::GetMilliSecond();
@ -43,16 +49,20 @@ namespace a8
// 保留后41位时间
value = time << 22;
// 中间10位是机器ID
value |= (machine_id & 0x3FF) << 12;
// 中间12位是机器ID
value |= (machine_id & MAX_MACHINE_ID) << SEQUNCE_ID_BIT_NUM;
// 最后10位是sequenceID
value |= sequence_id & MAX_SEQUNCE_ID;
// 最后12位是sequenceID
value |= sequence_id & 0xFFF;
return value;
}
void SnowFlake::SetMachineId(unsigned short machineid)
{
if (machineid > MAX_MACHINE_ID || machineid < 1) {
abort();
}
machine_id = machineid;
}
}

View File

@ -1,5 +1,5 @@
#ifndef A8_UUID_HPP
#define A8_UUID_HPP
#ifndef A8_UUID_H
#define A8_UUID_H
namespace a8
{
@ -7,21 +7,27 @@ namespace a8
{
const long long A8_EPOCH = 1419120000000LL;
//毫秒级时间41位+机器ID 10位+毫秒内序列12
const int MACHINE_ID_BIT_NUM = 12;
const int SEQUNCE_ID_BIT_NUM = 10;
const int MAX_MACHINE_ID = (1 << MACHINE_ID_BIT_NUM) - 1; //oldvalue: 0x3FF
const int MAX_SEQUNCE_ID = (1 << SEQUNCE_ID_BIT_NUM) - 1; //oldvalue: 0xFFF
//毫秒级时间41位+机器ID 12位+毫秒内序列10
class SnowFlake
{
public:
static long long FetchTime(long long value);
static int FetchMachineId(long long value);
static int FetchSequnceId(long long value);
public:
SnowFlake();
long long Generate();
void SetMachineId(unsigned short machineid);
private:
unsigned short machine_id = 0; //10 bit
unsigned short sequence_id = 0; //12 bit
unsigned short machine_id = 0; //12 bit
unsigned short sequence_id = 0; //10 bit
long long last_generate_tick = 0;
};
}

View File

@ -3,6 +3,7 @@
#include <a8/a8.h>
#include <a8/pyengine.h>
#include <a8/stringlist.h>
#include <a8/uuid.h>
#include "websocket_test.h"
#include "xml_test.h"
@ -31,6 +32,12 @@ void testpy()
int main(int argc, char* argv[])
{
a8::uuid::SnowFlake uuid;
uuid.SetMachineId(a8::uuid::MAX_MACHINE_ID);
long long id = uuid.Generate();
long long time = a8::uuid::SnowFlake::FetchTime(id);
int mac_id = a8::uuid::SnowFlake::FetchMachineId(id);
int seq_id = a8::uuid::SnowFlake::FetchSequnceId(id);
testpy();
#if 0
a8::PyEngine pyengine;