看来一下雪花算法的实现方法,用 c++试着实现了一下,这里仅仅是实现了算法的流程,但是具体的细节,如并发、多线程访问等等没有具体考虑。
雪花算法的简单讲解参考
#include <sys/select.h>
#include <iostream>
#include <chrono>
#include <random>
#include <ctime>
using namespace std;// 有序且全局唯一的 idlong long getTimeStamp() {return chrono::duration_cast<chrono::milliseconds>(chrono::system_clock::now().time_since_epoch()).count();
}// sleep 1ms
void sleep_ms(unsigned int ms) {struct timeval time;time.tv_sec = ms / 1000;time.tv_usec = (ms / 1000) % 1000000;select(0, NULL, NULL, NULL, &time);
}long long getNextMsTimeStamp() {sleep_ms(1);return getTimeStamp();
}long long getMachineId() {default_random_engine e;e.seed(getTimeStamp());return e() % 1024;
}long long lastTimeStamp = getTimeStamp();
long long sequence = 0;
long long sequenceMask = 0b111111111111;long long getSnowflaksUid() {// 一位标识符,表示正负long long identifier = 0;// 41位时间戳,69年long long timeStamp = getTimeStamp();// 十位工作机器位 1024 节点long long machine = getMachineId();if (lastTimeStamp == timeStamp) {// 获取当前时间戳,如果等于上次时间戳(同一毫秒内),则序列号加一;否则序列号赋值为0,从0开始sequence = (sequence + 1) & (sequenceMask); if (sequence == 0) {timeStamp = getNextMsTimeStamp();}} else {sequence = 0;}lastTimeStamp = timeStamp;return (timeStamp << 22) | (machine << 12) | sequence;
}int main() {cout << getSnowflaksUid() << endl;return 0;
}
关注我的微信公众号