| FazBrowse GitHub Viewer | Trending | | Home |
| Tools: [Download Repo ZIP] [Original HTTPS Page] |
| Name | Name | Last commit date | ||
|---|---|---|---|---|
English | 中文
A unique ID generator based on a timestamp or time series, inspired by Twitter's Snowflake.
The goal is to provide a unique identification (or UUID) solution that is reliable and flexible (configurable, extensible), but the performance is lower than the classical (fixed width and position) snowflake algorithm. Also provides the implementation of the classic snowflake algorithm(func Simple(server int64) func()int64). See Example 2
NOTES! ❗️Timestamp segment and sequence segment is REQUIRED!
go get github.com/StarryLab/tsid.gopackage main
import (
"flag"
"fmt"
. "github.com/StarryLab/tsid.go"
)
var (
host,
node int64
)
func init() {
// $> ./tsid -host=8 -node=6
host = *flag.Int64("host", 0, "data center(host) id")
node = *flag.Int64("node", 0, "server node id")
}
func main() {
b, e := Snowflake(host, node)
if e != nil {
fmt.Println("Error: ", e)
return
}
fmt.Println("TSID: ", b.NextString()) // strconv.FormatInt
}package main
import (
"flag"
"fmt"
. "github.com/StarryLab/tsid.go"
)
var (
server int64
)
func init() {
// $> ./tsid -server=8
server = *flag.Int64("server", 0, "server id")
}
func main() {
c, e := Simple(server)
if e != nil {
fmt.Println("Error: ", e)
return
}
for i := 0; i < 100; i++ {
fmt.Printf("%3d. %d", i+1, c())
}
}package examples
import (
"errors"
. "github.com/StarryLab/tsid.go"
)
func init() {
Register("my_data_source", DemoDataSource{{
"demo": 1,
"other": 9,
}})
}
type DemoDataSource struct{
data map[string]int64
}
func(d *DemoDataSource)Read(query ...interface{}) (int64, error) {
if len(query)>0 {
if s, o := query[0].(string); o {
if v, o := d.data[s]; o {
return v, nil
}
}
}
return 0, errors.New("data not found")
}package main
import (
"fmt"
_ "examples"
. "github.com/StarryLab/tsid.go"
)
func main() {
// Environment variable: SERVER_HOST, SERVER_NODE
opt := *O(
Sequence(12), // 12 bits, REQUIRED!
Env(6, "SERVER_HOST", 0), // 6 bits [0, 31], data center id
Env(4, "SERVER_NODE", 0), // 4 bits [0, 15], server node id
Data(10, "my_data_source", 2, "demo"),// 10 bits [0, 1023], data source
Random(30), // 30 bits
Timestamp(41, TimestampMilliseconds), // 41 bits, REQUIRED!
)
b, e := Make(opt)
if e != nil {
fmt.Println("Error: ", e)
return
}
fmt.Println("TSID: ", b.NextString()) // strconv.FormatInt
}| Back | FazBrowse Home | New Git URL |