You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
ntool/nrandom/snowflake/generator.go

52 lines
1012 B
Go

1 year ago
package snowflake
import (
"sync"
"time"
)
type Generator interface {
// NextID 生成一个唯一ID
NextID() int64
}
const sleepDuration = 200 * time.Millisecond
var (
mutex sync.Mutex
snowflakeInstance Generator
)
func GetDefaultInstance() Generator {
if snowflakeInstance == nil {
mutex.Lock()
snowflakeInstance = NewSnowWorkerOffset(nil)
time.Sleep(sleepDuration)
mutex.Unlock()
}
return snowflakeInstance
}
func SetSnowflake(options *Options) {
snowflakeInstance = NewSnowflake(options)
}
func NewSnowflake(options *Options) Generator {
mutex.Lock()
defer mutex.Unlock()
var snowflakeInstance Generator
switch options.Method {
case MethodSnowflakeOffset:
snowflakeInstance = NewSnowWorkerOffset(options)
time.Sleep(sleepDuration)
case MethodSnowflake:
fallthrough
default:
snowflakeInstance = NewSnowWorker(options)
}
return snowflakeInstance
}