├── .travis.yml ├── LICENSE ├── README.md ├── _config.yml ├── docs └── load.png ├── go.mod ├── go.sum ├── main.go └── snowflake ├── snowflake.go └── snowflake_test.go /.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | 3 | matrix: 4 | fast_finish: true 5 | include: 6 | - go: 1.11.x 7 | env: GO111MODULE=on 8 | - go: 1.12.x 9 | env: GO111MODULE=on 10 | - go: 1.13.x 11 | - go: master 12 | 13 | before_install: 14 | - if [[ "${GO111MODULE}" = "on" ]]; then go mod download; fi 15 | - if [[ "${GO111MODULE}" = "on" ]]; then export PATH="${GOPATH}/bin:${GOROOT}/bin:${PATH}"; fi 16 | 17 | install: 18 | - go get github.com/golang/glog 19 | 20 | script: 21 | - go test -v ./snowflake 22 | - go run ./main.go 23 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ❄️ GO-Snowflake 2 | 3 | [![Build Status](https://travis-ci.com/GUAIK-ORG/go-snowflake.svg?branch=master)](https://travis-ci.com/GUAIK-ORG/go-snowflake) 4 | 5 | ## Snowflake简介 6 | 7 | 在单机系统中我们会使用自增id作为数据的唯一id,自增id在数据库中有利于排序和索引,但是在分布式系统中如果还是利用数据库的自增id会引起冲突,自增id非常容易被爬虫爬取数据。在分布式系统中有使用uuid作为数据唯一id的,但是uuid是一串随机字符串,所以它无法被排序。 8 | 9 | Twitter设计了Snowflake算法为分布式系统生成ID,Snowflake的id是int64类型,它通过datacenterId和workerId来标识分布式系统,下面看下它的组成: 10 | 11 | | 1bit | 41bit | 5bit | 5bit | 12bit | 12 | |---|---|---|---|---| 13 | | 符号位(保留字段) | 时间戳(当前时间-纪元时间) | 数据中心id | 机器id | 自增序列 14 | 15 | ### 算法简介 16 | 17 | 在使用Snowflake生成id时,首先会计算时间戳timestamp(当前时间 - 纪元时间),如果timestamp数据超过41bit则异常。同样需要判断datacenterId和workerId不能超过5bit(0-31),在处理自增序列时,如果发现自增序列超过12bit时需要等待,因为当前毫秒下12bit的自增序列被用尽,需要进入下一毫秒后自增序列继续从0开始递增。 18 | 19 | --- 20 | 21 | ## 🚀 快速开始 22 | 23 | ### 🕹 克隆 & 运行 24 | 25 | ```bash 26 | git clone https://github.com/GUAIK-ORG/go-snowflake.git 27 | 28 | go run main.go 29 | ``` 30 | 31 | ### 💾 安装 & 导入 32 | 33 | ```bash 34 | go get github.com/GUAIK-ORG/go-snowflake 35 | 36 | // 在项目中导入模块 37 | import "github.com/GUAIK-ORG/go-snowflake/snowflake" 38 | ``` 39 | 40 | ### ⚠️注意事项 41 | 42 | * 在多实例(多个snowflake对象)的并发环境下,请确保每个实例(datacenterid,workerid)的唯一性,否则生成的ID可能冲突。 43 | 44 | ### 📊 测试 45 | 46 | 本机测试: 47 | 48 | | 参数 | 配置 | 49 | |---|---| 50 | | OS | MacBook Pro (13-inch, Late 2016, Four Thunderbolt 3 Ports)| 51 | | CPU | 2.9 GHz 双核Intel Core i5 | 52 | | RAM | 8 GB 2133 MHz LPDDR3 | 53 | 54 | > 测试代码 55 | 56 | ```go 57 | func TestLoad() { 58 | var wg sync.WaitGroup 59 | s, err := snowflake.NewSnowflake(int64(0), int64(0)) 60 | if err != nil { 61 | glog.Error(err) 62 | return 63 | } 64 | var check sync.Map 65 | t1 := time.Now() 66 | for i := 0; i < 200000; i++ { 67 | wg.Add(1) 68 | go func() { 69 | defer wg.Done() 70 | val := s.NextVal() 71 | if _, ok := check.Load(val); ok { 72 | // id冲突检查 73 | glog.Error(fmt.Errorf("error#unique: val:%v", val)) 74 | return 75 | } 76 | check.Store(val, 0) 77 | if val == 0 { 78 | glog.Error(fmt.Errorf("error")) 79 | return 80 | } 81 | }() 82 | } 83 | wg.Wait() 84 | elapsed := time.Since(t1) 85 | glog.Infof("generate 20k ids elapsed: %v", elapsed) 86 | } 87 | ``` 88 | 89 | > 运行结果 90 | 91 | ![load](https://gitee.com/GuaikOrg/go-snowflake/raw/master/docs/load.png) 92 | 93 | ## 🗂 使用说明 94 | 95 | ### 创建Snowflake对象 96 | 97 | ```go 98 | // NewSnowflake(datacenterid, workerid int64) (*Snowflake, error) 99 | // 参数1 (int64): 数据中心ID (可用范围:0-31) 100 | // 参数2 (int64): 机器ID (可用范围:0-31) 101 | // 返回1 (*Snowflake): Snowflake对象 | nil 102 | // 返回2 (error): 错误码 103 | s, err := snowflake.NewSnowflake(int64(0), int64(0)) 104 | if err != nil { 105 | glog.Error(err) 106 | return 107 | } 108 | ``` 109 | 110 | ### 生成唯一ID 111 | 112 | ```go 113 | s, err := snowflake.NewSnowflake(int64(0), int64(0)) 114 | // ...... 115 | // (s *Snowflake) NextVal() int64 116 | // 返回1 (int64): 唯一ID 117 | id := s.NextVal() 118 | // ...... 119 | ``` 120 | 121 | ### 通过ID获取数据中心ID与机器ID 122 | 123 | ```go 124 | // ...... 125 | // GetDeviceID(sid int64) (datacenterid, workerid int64) 126 | // 参数1 (int64): 唯一ID 127 | // 返回1 (int64): 数据中心ID 128 | // 返回2 (int64): 机器ID 129 | datacenterid, workerid := snowflake.GetDeviceID(id)) 130 | ``` 131 | 132 | ### 通过ID获取时间戳(创建ID时的时间戳 - epoch) 133 | 134 | ```go 135 | // ...... 136 | // GetTimestamp(sid int64) (timestamp int64) 137 | // 参数1 (int64): 唯一ID 138 | // 返回1 (int64): 从epoch开始计算的时间戳 139 | t := snowflake.GetTimestamp(id) 140 | ``` 141 | 142 | ### 通过ID获取生成ID时的时间戳 143 | 144 | ```go 145 | // ...... 146 | // GetGenTimestamp(sid int64) (timestamp int64) 147 | // 参数1 (int64): 唯一ID 148 | // 返回1 (int64): 唯一ID生成时的时间戳 149 | t := snowflake.GetGenTimestamp(id) 150 | ``` 151 | 152 | ### 通过ID获取生成ID时的时间(精确到:秒) 153 | 154 | ```go 155 | // ...... 156 | // GetGenTime(sid int64) 157 | // 参数1 (int64): 唯一ID 158 | // 返回1 (string): 唯一ID生成时的时间 159 | tStr := snowflake.GetGenTime(id) 160 | ``` 161 | 162 | ### 查看时间戳字段使用占比(41bit能存储的范围:从epoch开始往后69年) 163 | 164 | ```go 165 | // ...... 166 | // GetTimestampStatus() (state float64) 167 | // 返回1 (float64): 时间戳字段使用占比(范围 0.0 - 1.0) 168 | status := snowflake.GetTimestampStatus() 169 | ``` 170 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-time-machine -------------------------------------------------------------------------------- /docs/load.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GUAIK-ORG/go-snowflake/220c4260e85f8507a670a625a76f8e26ba989daf/docs/load.png -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/GUAIK-ORG/go-snowflake 2 | 3 | go 1.12 4 | 5 | require github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b 6 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58= 2 | github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= 3 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "runtime" 7 | "sync" 8 | "time" 9 | 10 | "github.com/GUAIK-ORG/go-snowflake/snowflake" 11 | 12 | "github.com/golang/glog" 13 | ) 14 | 15 | func TestLoad() { 16 | var wg sync.WaitGroup 17 | s, err := snowflake.NewSnowflake(int64(0), int64(0)) 18 | if err != nil { 19 | glog.Error(err) 20 | return 21 | } 22 | var check sync.Map 23 | t1 := time.Now() 24 | for i := 0; i < 200000; i++ { 25 | wg.Add(1) 26 | go func() { 27 | defer wg.Done() 28 | val := s.NextVal() 29 | if _, ok := check.Load(val); ok { 30 | // id冲突检查 31 | glog.Error(fmt.Errorf("error#unique: val:%v", val)) 32 | return 33 | } 34 | check.Store(val, 0) 35 | if val == 0 { 36 | glog.Error(fmt.Errorf("error")) 37 | return 38 | } 39 | }() 40 | } 41 | wg.Wait() 42 | elapsed := time.Since(t1) 43 | glog.Infof("generate 20k ids elapsed: %v", elapsed) 44 | } 45 | 46 | func TestGenID() { 47 | s, err := snowflake.NewSnowflake(int64(0), int64(0)) 48 | if err != nil { 49 | glog.Error(err) 50 | return 51 | } 52 | for i := 0; i < 5; i++ { 53 | val := s.NextVal() 54 | glog.Infof("id: %v, time:%v", val, snowflake.GetGenTime(val)) 55 | } 56 | 57 | } 58 | 59 | func main() { 60 | flag.Set("alsologtostderr", "true") 61 | flag.Set("log_dir", "/log") 62 | flag.Set("v", "3") 63 | flag.Parse() 64 | defer func() { 65 | glog.Flush() 66 | }() 67 | runtime.GOMAXPROCS(runtime.NumCPU()) 68 | TestGenID() 69 | // 测试生成20万id的速度 70 | TestLoad() 71 | // 获取时间戳字段已经使用的占比(0.0 - 1.0) 72 | // 默认开始时间为:2020年01月01日 00:00:00 73 | glog.Infof("Timestamp status: %f", snowflake.GetTimestampStatus()) 74 | } 75 | -------------------------------------------------------------------------------- /snowflake/snowflake.go: -------------------------------------------------------------------------------- 1 | package snowflake 2 | 3 | import ( 4 | "fmt" 5 | "sync" 6 | "time" 7 | 8 | "github.com/golang/glog" 9 | ) 10 | 11 | const ( 12 | epoch = int64(1577808000000) // 设置起始时间(时间戳/毫秒):2020-01-01 00:00:00,有效期69年 13 | timestampBits = uint(41) // 时间戳占用位数 14 | datacenteridBits = uint(5) // 数据中心id所占位数 15 | workeridBits = uint(5) // 机器id所占位数 16 | sequenceBits = uint(12) // 序列所占的位数 17 | timestampMax = int64(-1 ^ (-1 << timestampBits)) // 时间戳最大值 18 | datacenteridMax = int64(-1 ^ (-1 << datacenteridBits)) // 支持的最大数据中心id数量 19 | workeridMax = int64(-1 ^ (-1 << workeridBits)) // 支持的最大机器id数量 20 | sequenceMask = int64(-1 ^ (-1 << sequenceBits)) // 支持的最大序列id数量 21 | workeridShift = sequenceBits // 机器id左移位数 22 | datacenteridShift = sequenceBits + workeridBits // 数据中心id左移位数 23 | timestampShift = sequenceBits + workeridBits + datacenteridBits // 时间戳左移位数 24 | ) 25 | 26 | type Snowflake struct { 27 | sync.Mutex 28 | timestamp int64 29 | workerid int64 30 | datacenterid int64 31 | sequence int64 32 | } 33 | 34 | func NewSnowflake(datacenterid, workerid int64) (*Snowflake, error) { 35 | if datacenterid < 0 || datacenterid > datacenteridMax { 36 | return nil, fmt.Errorf("datacenterid must be between 0 and %d", datacenteridMax-1) 37 | } 38 | if workerid < 0 || workerid > workeridMax { 39 | return nil, fmt.Errorf("workerid must be between 0 and %d", workeridMax-1) 40 | } 41 | return &Snowflake{ 42 | timestamp: 0, 43 | datacenterid: datacenterid, 44 | workerid: workerid, 45 | sequence: 0, 46 | }, nil 47 | } 48 | 49 | func (s *Snowflake) NextVal() int64 { 50 | s.Lock() 51 | now := time.Now().UnixNano() / 1000000 // 转毫秒 52 | if s.timestamp == now { 53 | // 当同一时间戳(精度:毫秒)下多次生成id会增加序列号 54 | s.sequence = (s.sequence + 1) & sequenceMask 55 | if s.sequence == 0 { 56 | // 如果当前序列超出12bit长度,则需要等待下一毫秒 57 | // 下一毫秒将使用sequence:0 58 | for now <= s.timestamp { 59 | now = time.Now().UnixNano() / 1000000 60 | } 61 | } 62 | } else { 63 | // 不同时间戳(精度:毫秒)下直接使用序列号:0 64 | s.sequence = 0 65 | } 66 | t := now - epoch 67 | if t > timestampMax { 68 | s.Unlock() 69 | glog.Errorf("epoch must be between 0 and %d", timestampMax-1) 70 | return 0 71 | } 72 | s.timestamp = now 73 | r := int64((t)<> datacenteridShift) & datacenteridMax 81 | workerid = (sid >> workeridShift) & workeridMax 82 | return 83 | } 84 | 85 | // 获取时间戳 86 | func GetTimestamp(sid int64) (timestamp int64) { 87 | timestamp = (sid >> timestampShift) & timestampMax 88 | return 89 | } 90 | 91 | // 获取创建ID时的时间戳 92 | func GetGenTimestamp(sid int64) (timestamp int64) { 93 | timestamp = GetTimestamp(sid) + epoch 94 | return 95 | } 96 | 97 | // 获取创建ID时的时间字符串(精度:秒) 98 | func GetGenTime(sid int64) (t string) { 99 | // 需将GetGenTimestamp获取的时间戳/1000转换成秒 100 | t = time.Unix(GetGenTimestamp(sid)/1000, 0).Format("2006-01-02 15:04:05") 101 | return 102 | } 103 | 104 | // 获取时间戳已使用的占比:范围(0.0 - 1.0) 105 | func GetTimestampStatus() (state float64) { 106 | state = float64((time.Now().UnixNano()/1000000 - epoch)) / float64(timestampMax) 107 | return 108 | } 109 | -------------------------------------------------------------------------------- /snowflake/snowflake_test.go: -------------------------------------------------------------------------------- 1 | package snowflake 2 | 3 | import ( 4 | "sync" 5 | "testing" 6 | ) 7 | 8 | func TestNewSnowflake(t *testing.T) { 9 | var i, j int64 10 | for i = 0; i < 32; i++ { 11 | for j = 0; j < 32; j++ { 12 | _, err := NewSnowflake(i, j) 13 | if err != nil { 14 | t.Error(err) 15 | } 16 | } 17 | } 18 | } 19 | 20 | func TestNextVal(t *testing.T) { 21 | s, err := NewSnowflake(0, 0) 22 | if err != nil { 23 | t.Error(err) 24 | } 25 | var i int64 26 | for i = 0; i < sequenceMask*10; i++ { 27 | val := s.NextVal() 28 | if val == 0 { 29 | t.Fail() 30 | } 31 | } 32 | } 33 | 34 | func TestUnique(t *testing.T) { 35 | var wg sync.WaitGroup 36 | var check sync.Map 37 | s, err := NewSnowflake(0, 0) 38 | if err != nil { 39 | t.Error(err) 40 | } 41 | for i := 0; i < 1000000; i++ { 42 | wg.Add(1) 43 | go func() { 44 | defer wg.Add(-1) 45 | val := s.NextVal() 46 | if _, ok := check.Load(val); ok { 47 | t.Fail() 48 | return 49 | } 50 | check.Store(val, 0) 51 | if val == 0 { 52 | t.Fail() 53 | return 54 | } 55 | }() 56 | } 57 | wg.Wait() 58 | } 59 | 60 | func TestGetTime(t *testing.T) { 61 | s, err := NewSnowflake(0, 1) 62 | if err != nil { 63 | t.Error(err) 64 | } 65 | val := s.NextVal() 66 | t.Logf("time:%v", GetGenTime(val)) 67 | } 68 | 69 | func TestGetDeviceID(t *testing.T) { 70 | s, err := NewSnowflake(28, 11) 71 | if err != nil { 72 | t.Error(err) 73 | } 74 | val := s.NextVal() 75 | datacenterid, workerid := GetDeviceID(val) 76 | if datacenterid != 28 || workerid != 11 { 77 | t.Fail() 78 | } 79 | } 80 | --------------------------------------------------------------------------------