From a7a70636ddcf6a3faea7a8fc4c8941e6c31e2159 Mon Sep 17 00:00:00 2001 From: Jack Date: Fri, 30 Oct 2020 12:33:56 +0800 Subject: [PATCH] improve snowflake number generating for package guid --- util/guid/guid_number.go | 25 ++++++++++++------------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/util/guid/guid_number.go b/util/guid/guid_number.go index 7377e4474..9cda36a8b 100644 --- a/util/guid/guid_number.go +++ b/util/guid/guid_number.go @@ -23,12 +23,23 @@ var ( // MachineId is 16 bits number composed with the last two parts of the first local private ip. // You can change it as your custom machine id in boot time, but do not change it in runtime. // Note that if there's no net card on the machine, it panics when the process boots. - MachineId = getLower16BitPrivateIP() + MachineId uint16 // sequenceNumber is used for internal concurrent-safe sequence number counting. sequenceNumber = gtype.NewInt() ) +func init() { + if MachineId != 0 { + return + } + ip, err := getPrivateIPv4() + if err != nil { + panic(err) + } + MachineId = uint16(ip[2])<<8 + uint16(ip[3]) +} + // I creates and returns an uint64 id which using improved SnowFlake algorithm. // An Improved SnowFlake ID is composed of: // 39 bits for time in units of 10 msec @@ -38,18 +49,6 @@ func I() uint64 { return uint64(time.Now().UnixNano())<<(BitLenMachineID+BitLenSequence) | uint64(MachineId<