项目作者: kaelzhang

项目描述 :
Egg plugin to generate unique and increased twitter-snowflake uuid.
高级语言: JavaScript
项目地址: git://github.com/kaelzhang/egg-snowflake.git
创建时间: 2017-12-29T15:13:33Z
项目社区:https://github.com/kaelzhang/egg-snowflake

开源协议:MIT License

下载


Build Status
Coverage



Deprecation Warning

Since this library only works for cluster mode of egg which is not a best practice for the de facto container-based server-side solutions such as Kubernetes.

So I will archived this project and turn it into readonly mode.


egg-snowflake

Egg plugin to generate unique and increased twitter-snowflake uuid.

egg-snowflake will first assign a unique worker id to each worker by using the IPC messaging, and then create uuid according to the twitter snowflake algorithm.

Install

  1. $ npm install egg-snowflake

Configurations

config/plugin.js

  1. exports.snowflake = {
  2. enable: true,
  3. package: 'egg-snowflake'
  4. }

config/config.default.js

  1. // |--- timestamp ---|- machine -|- worker -|-- serial --|
  2. // |----- 41 bit ----|---- 6 ----|--- 4 ----|---- 12 ----|
  3. // | | | | |
  4. // 00000000000000000 000001 0000 000000000000
  5. exports.snowflake = {
  6. client: {
  7. machineId: 1,
  8. // `Number` if 6-bit length (the default value),
  9. // we could handle servers from `2 ** 6` different machines.
  10. // And if 0, there will be no machine id in the uuid
  11. machineIdBitLength: 6,
  12. workerIdBitLength: 4,
  13. // Could handle max 4096 requests per millisecond
  14. serialIdBitLength: 12
  15. }
  16. }

Then:

  1. ...
  2. async doSomething () {
  3. const {snowflake} = this.app
  4. const uuid = await snowflake.uuid()
  5. console.log(uuid)
  6. // '6352534847126241280'
  7. const workerId = await snowflake.index()
  8. console.log(workerId)
  9. // 0
  10. }
  11. ...

await snowflake.uuid()

Generates the unique and time-based id across workers (/ machines)

Returns String | Promise<String> instead of Number due to the bad accuracy of JavaScript.

The bit-length of the return value equals to:

  1. 41 + machineIdBitLength + workerIdBitLength + serialIdBitLength

So you could use the three configuration options to handle the length of uuids.

await snowflake.index()

Returns String | Promise<Number> the 0-index unique worker id of the current cluster.

License

MIT