下表是生成uuid 库的比较,可以根据实际需求选择相应的库

0pPKHjWprnVxGH7dEsAoXX2YQvUb50vl5e54p1000fo3gh0-Kmdih_fs4ZZccpx2Hl120f8707d600010801BJMVNPBBZC3E36FJTGVF0C4S1JADkqpWxPx-4qaWY47~FqI5b52d72c-82b3-4f8e-beb5-437a974842c

另外一些库

基于时间的 uuid 例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package main

 import (
 	"crypto/rand"
 	"fmt"
 	"time"
 )

 func main() {
 	// generate 32 bits timestamp
 	unix32bits := uint32(time.Now().UTC().Unix())

 	buff := make([]byte, 12)

 	numRead, err := rand.Read(buff)

 	if numRead != len(buff) || err != nil {
 		panic(err)
 	}

 	fmt.Printf("%x-%x-%x-%x-%x-%x\n", unix32bits, buff[0:2], buff[2:4], buff[4:6], buff[6:8], buff[8:])
 }

输出:

1
59658c4d-5b7e-bd35-b887-c6f4-41bcc1be
/usr/bin/uuidgennu7hatch/gouuidsatori/go.uuid
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package main

import (
    "fmt"
    "log"
    "os/exec"
)

func main() {
    out, err := exec.Command("uuidgen").Output()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("%s", out)
}

输出:

1
FEDDB383-F25D-4F08-A40C-FF7D587417C3

一般场景推荐使用 https://github.com/rs/xid,其性能好、字符串较短,特性如下:

1
2
3
4
5
6
7
Size: 12 bytes (96 bits), smaller than UUID, larger than snowflake
Base32 hex encoded by default (20 chars when transported as printable string, still sortable)
Non configured, you don't need set a unique machine and/or data center id
K-ordered
Embedded time with 1 second precision
Unicity guaranteed for 16,777,216 (24 bits) unique ids per second and per host/process
Lock-free (i.e.: unlike UUIDv1 and v2)
Xid/dev/urandomcrypto/rand

本文网址: https://golangnote.com/topic/177.html 转摘请注明来源