Generate creates and returns a unique snowflake ID To help guarantee uniqueness - Make sure your system is keeping accurate system time - Make sure you never have multiple nodes running with the same node ID
()
| 133 | // - Make sure your system is keeping accurate system time |
| 134 | // - Make sure you never have multiple nodes running with the same node ID |
| 135 | func (n *Node) Generate() ID { |
| 136 | |
| 137 | n.mu.Lock() |
| 138 | |
| 139 | now := time.Since(n.epoch).Nanoseconds() / 1000000 |
| 140 | |
| 141 | if now == n.time { |
| 142 | n.step = (n.step + 1) & n.stepMask |
| 143 | |
| 144 | if n.step == 0 { |
| 145 | for now <= n.time { |
| 146 | now = time.Since(n.epoch).Nanoseconds() / 1000000 |
| 147 | } |
| 148 | } |
| 149 | } else { |
| 150 | n.step = 0 |
| 151 | } |
| 152 | |
| 153 | n.time = now |
| 154 | |
| 155 | r := ID((now)<<n.timeShift | |
| 156 | (n.node << n.nodeShift) | |
| 157 | (n.step), |
| 158 | ) |
| 159 | |
| 160 | n.mu.Unlock() |
| 161 | return r |
| 162 | } |
| 163 | |
| 164 | // Int64 returns an int64 of the snowflake ID |
| 165 | func (f ID) Int64() int64 { |