1.SnowFlake.h
#ifndef _SNOW_FLAKE_H_
#define _SNOW_FLAKE_H_
#include <string>
#include <stdint.h>
typedef long long int64;
class SnowFlake {
public:
SnowFlake();
~SnowFlake();
int64 getServerIdAsLong();
int64 getNextId(int64 epoch);
private:
int64 generateId(int64 epoch, int64 next, int64 shareid);
int64 m_offset;
int64 m_last;
int64 m_shareid;
};
#endif
2.SnowFlake.cpp
#include <iostream>
#include <unistd.h>
#include <netdb.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <time.h>
#include "SnowFlake.h"
#define MAX_NEXT 0b1111111111111111L
#define OFFSET 946656000L
using namespace std;
SnowFlake::SnowFlake()
{
m_offset = 0;
m_last = 0;
m_shareid = getServerIdAsLong();
m_shareid &= 0x1f;
}
SnowFlake::~SnowFlake()
{
}
int64 SnowFlake::getServerIdAsLong()
{
struct hostent *host = NULL;
char name[256];
char szIp[32];
int64 lIp;
const char *ret = NULL;
gethostname(name, sizeof(name));
host = gethostbyname(name);
ret = inet_ntop(host->h_addrtype, host->h_addr_list[0], szIp, sizeof(szIp));
if(ret == NULL)
{
cout << "hostname transform to ip failed" << endl;
return -1;
}
lIp = htonl(inet_addr(szIp));
return lIp;
}
int64 SnowFlake::getNextId(int64 epoch)
{
int64 next;
if(epoch < m_last)
{
cout << "clock is back: " << epoch << " from previous: " << m_last << endl;
epoch = m_last;
}
if(m_last != epoch)
{
m_last = epoch;
m_offset = 0;
}
m_offset++;
next = m_offset & MAX_NEXT;
if(next == 0)
{
cout << "maximum id reached in 1 second in epoch: " << endl;
return getNextId(epoch+1);
}
return generateId(epoch, next, m_shareid);
}
int64 SnowFlake::generateId(int64 epoch, int64 next, int64 shareid)
{
return ((epoch-OFFSET) << 21 | (next << 5) | shareid);
}
int main()
{
SnowFlake sf;
struct timeval tv;
gettimeofday(&tv, NULL);
cout << sf.getNextId(tv.tv_sec) << endl;
cout << sf.getNextId(tv.tv_sec) << endl;
cout << sf.getNextId(tv.tv_sec) << endl;
return 0;
}
3.编译源码
$ g++ -o SnowFlake SnowFlake.cpp -std=c++11
4.运行及其结果
$ ./SnowFlake
1446378012147745
1446378012147777
1446378012147809
网友评论