最近项目中使用了SnowFlake算法产生ID,并在实际运行环境下会产生重复ID,所以写了一个Go的程序进行验证,顺便也练习一下Go的协程与通道。
至于GO的协程和通道的基础知识请自行百度。
代码如下:
package main
import (
"fmt"
"github.com/zheng-ji/goSnowFlake"
)
func main() {
fmt.Println("Hell Go !")
iw, err := goSnowFlake.NewIdWorker(1)
if err != nil {
fmt.Println(err)
}
cons := map[int64]int{}
chncount := 10
chs := make([]chan int, chncount)
for j := 0; j < chncount; j++ {
chs[j] = make(chan int)
go func(idx int) {
for i := 0; i < 10000; i++ {
if id, err := iw.NextId(); err == nil {
if _, ok := cons[id]; ok {
fmt.Println(idx, " ", id)
}
}
}
chs[idx] <- 1
}(j)
}
for i := 0; i < chncount; i++ {
<-chs[i]
}
}
运行结果如下:
GOROOT=C:\Go #gosetup GOPATH=D:\GO\TestPros;D:\GO\TestPros\src;D:\GO\GOPATH #gosetup C:\Go\bin\go.exe build -i -o D:\GO\TestPros\bin\TestPros.exe D:/GO/TestPros/src/goroutine.go #gosetup "C:\Program Files\JetBrains\GoLand 2018.1.1\bin\runnerw.exe" D:\GO\TestPros\bin\TestPros.exe #gosetup Hell Go ! Process finished with exit code 0
共使用了10个协程,每个协程产生1000个ID,但是通过验证没有重复字段。可能验证的不够完整,但是目前尚未找到原因。
原文:https://www.cnblogs.com/veviDP/p/8908797.html