forked from admpub/nging
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sonyflake.go
101 lines (88 loc) · 2.4 KB
/
sonyflake.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/*
Nging is a toolbox for webmasters
Copyright (C) 2018-present Wenhui Shen <swh@admpub.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package common
import (
"fmt"
"strings"
"time"
"github.com/admpub/sonyflake"
)
var (
sonyFlakes = map[uint16]*sonyflake.Sonyflake{}
SonyflakeStartDate = `2018-09-01 08:08:08`
)
//NewSonyflake 19位
func NewSonyflake(startDate string, machineIDs ...uint16) (*sonyflake.Sonyflake, error) {
if !strings.Contains(startDate, ` `) {
startDate += ` 00:00:00`
}
startTime, err := time.ParseInLocation(`2006-01-02 15:04:05`, startDate, time.Local)
if err != nil {
return nil, err
}
var machineID uint16
if len(machineIDs) > 0 {
machineID = machineIDs[0]
}
st := sonyflake.Settings{
StartTime: startTime,
MachineID: func() (uint16, error) {
return machineID, nil
},
CheckMachineID: func(id uint16) bool {
return machineID == id
},
}
return sonyflake.NewSonyflake(st), err
}
func init() {
SonyflakeInit(0)
}
func SonyflakeInit(machineIDs ...uint16) {
err := SetSonyflake(SonyflakeStartDate)
if err != nil {
panic(err)
}
}
func SetSonyflake(startDate string, machineIDs ...uint16) (err error) {
sonyFlake, err := NewSonyflake(startDate, machineIDs...)
if err != nil {
return err
}
var machineID uint16
if len(machineIDs) > 0 {
machineID = machineIDs[0]
}
sonyFlakes[machineID] = sonyFlake
return err
}
func UniqueID(machineIDs ...uint16) (string, error) {
id, err := NextID(machineIDs...)
if err != nil {
return ``, err
}
return fmt.Sprintf(`%d`, id), nil
}
func NextID(machineIDs ...uint16) (uint64, error) {
var machineID uint16
if len(machineIDs) > 0 {
machineID = machineIDs[0]
}
sonyFlake, ok := sonyFlakes[machineID]
if !ok || sonyFlake == nil {
SonyflakeInit(machineID)
}
return sonyFlake.NextID()
}