[关闭]
@lupnfer 2017-04-11T11:12:35.000000Z 字数 2020 阅读 799

SnowFlake

Code


python

  1. def make_snowflake(timestamp_ms, datacenter_id, worker_id, sequence_id, twepoch=twepoch):
  2. """generate a twitter-snowflake id, based on
  3. https://github.com/twitter/snowflake/blob/master/src/main/scala/com/twitter/service/snowflake/IdWorker.scala
  4. :param: timestamp_ms time since UNIX epoch in milliseconds"""
  5. sid = ((int(timestamp_ms) - twepoch) % max_timestamp) << datacenter_id_bits << worker_id_bits << sequence_id_bits
  6. sid += (datacenter_id % max_datacenter_id) << worker_id_bits << sequence_id_bits
  7. sid += (worker_id % max_worker_id) << sequence_id_bits
  8. sid += sequence_id % max_sequence_id
  9. return sid
  10. #snowflake 生成content
  11. t0 = int(time.time() * 1000)
  12. dentialsInfo.strCredentials_content = make_snowflake(t0, 1, 2, 3)

uuid.h

  1. #ifndef __UTIL_UUID_H__
  2. #define __UTIL_UUID_H__
  3. #include <stdint.h>
  4. namespace utils
  5. {
  6. // twitter snowflake算法
  7. // 64 63--------------22---------12---------0
  8. // 符号位 | 41位时间 |10位机器码|12位自增码|
  9. extern uint64_t get_time();
  10. class unique_id_t
  11. {
  12. public:
  13. unique_id_t();
  14. ~unique_id_t();
  15. void set_epoch(uint64_t epoch);
  16. void set_machine(int32_t machine);
  17. int64_t generate();
  18. private:
  19. uint64_t epoch_;
  20. uint64_t time_;
  21. int32_t machine_;
  22. int32_t sequence_;
  23. };
  24. }
  25. #endif // !__UTIL_UUID_H__
  1. #include "uuid.h"
  2. #include <sys/time.h>
  3. #include <unistd.h>
  4. #define EPOCHFILETIME 11644473600000000ULL
  5. namespace utils
  6. {
  7. uint64_t get_time()
  8. {
  9. struct timeval tv;
  10. gettimeofday(&tv, NULL);
  11. uint64_t time = tv.tv_usec;
  12. time /= 1000;
  13. time += (tv.tv_sec * 1000);
  14. return time;
  15. }
  16. unique_id_t::unique_id_t()
  17. {
  18. epoch_ = 0;
  19. time_ = 0;
  20. machine_ = 0;
  21. sequence_ = 0;
  22. }
  23. unique_id_t::~unique_id_t()
  24. {
  25. }
  26. void unique_id_t::set_epoch(uint64_t epoch)
  27. {
  28. epoch_ = epoch;
  29. }
  30. void unique_id_t::set_machine(int32_t machine)
  31. {
  32. machine_ = machine;
  33. }
  34. int64_t unique_id_t::generate()
  35. {
  36. int64_t value = 0;
  37. uint64_t time = get_time() - epoch_;
  38. // 保留后41位时间
  39. value = time << 22;
  40. // 中间10位是机器ID
  41. value |= (machine_ & 0x3FF) << 12;
  42. // 最后12位是sequenceID
  43. value |= sequence_++ & 0xFFF;
  44. if (sequence_ == 0x1000)
  45. {
  46. sequence_ = 0;
  47. }
  48. return value;
  49. }
  50. }
  51. #include <iostream>
  52. int main()
  53. {
  54. utils::unique_id_t* u_id_ptr = new utils::unique_id_t();
  55. u_id_ptr->set_epoch(uint64_t(1367505795100));
  56. u_id_ptr->set_machine(int32_t(100));
  57. for (int i = 0; i < 1024; ++i)
  58. {
  59. std::cout << u_id_ptr->generate() << std::endl;;
  60. }
  61. return 0;
  62. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注