update at 2020-07-20 10:06:17 by ehlxr

This commit is contained in:
ehlxr
2020-07-20 10:06:17 +08:00
parent cc3dec7cf5
commit e6c62d0bda
8 changed files with 305 additions and 43 deletions

76
utils/SnowFlake.go Normal file
View File

@@ -0,0 +1,76 @@
package util
import (
"errors"
"sync"
"time"
)
// 因为snowFlake目的是解决分布式下生成唯一id 所以ID中是包含集群和节点编号在内的
const (
workerBits uint8 = 10 // 每台机器(节点)的ID位数 10位最大可以有2^10=1024个节点
numberBits uint8 = 12 // 表示每个集群下的每个节点1毫秒内可生成的id序号的二进制位数 即每毫秒可生成 2^12-1=4096个唯一ID
// 这里求最大值使用了位运算,-1 的二进制表示为 1 的补码,感兴趣的同学可以自己算算试试 -1 ^ (-1 << nodeBits) 这里是不是等于 1023
workerMax int64 = -1 ^ (-1 << workerBits) // 节点ID的最大值用于防止溢出
numberMax int64 = -1 ^ (-1 << numberBits) // 同上用来表示生成id序号的最大值
timeShift uint8 = workerBits + numberBits // 时间戳向左的偏移量
workerShift uint8 = numberBits // 节点ID向左的偏移量
// 41位字节作为时间戳数值的话 大约68年就会用完
// 假如你2010年1月1日开始开发系统 如果不减去2010年1月1日的时间戳 那么白白浪费40年的时间戳啊
// 这个一旦定义且开始生成ID后千万不要改了 不然可能会生成相同的ID
epoch int64 = 1525705533000 // 这个是我在写epoch这个变量时的时间戳(毫秒)
)
// 定义一个woker工作节点所需要的基本参数
type Worker struct {
mu sync.Mutex // 添加互斥锁 确保并发安全
timestamp int64 // 记录时间戳
workerId int64 // 该节点的ID
number int64 // 当前毫秒已经生成的id序列号(从0开始累加) 1毫秒内最多生成4096个ID
}
// 实例化一个工作节点
func NewWorker(workerId int64) (*Worker, error) {
// 要先检测workerId是否在上面定义的范围内
if workerId < 0 || workerId > workerMax {
return nil, errors.New("Worker ID excess of quantity")
}
// 生成一个新节点
return &Worker{
timestamp: 0,
workerId: workerId,
number: 0,
}, nil
}
// 接下来我们开始生成id
// 生成方法一定要挂载在某个woker下这样逻辑会比较清晰 指定某个节点生成id
func (w *Worker) GetId() int64 {
// 获取id最关键的一点 加锁 加锁 加锁
w.mu.Lock()
defer w.mu.Unlock() // 生成完成后记得 解锁 解锁 解锁
// 获取生成时的时间戳
now := time.Now().UnixNano() / 1e6 // 纳秒转毫秒
if w.timestamp == now {
w.number++
// 这里要判断当前工作节点是否在1毫秒内已经生成numberMax个ID
if w.number > numberMax {
// 如果当前工作节点在1毫秒内生成的ID已经超过上限 需要等待1毫秒再继续生成
for now <= w.timestamp {
now = time.Now().UnixNano() / 1e6
}
}
} else {
// 如果当前时间与工作节点上一次生成ID的时间不一致 则需要重置工作节点生成ID的序号
w.number = 0
w.timestamp = now // 将机器上一次生成ID的时间更新为当前时间
}
// 第一段 now - epoch 为该算法目前已经奔跑了xxx毫秒
// 如果在程序跑了一段时间修改了epoch这个值 可能会导致生成相同的ID
ID := int64((now-epoch)<<timeShift | (w.workerId << workerShift) | (w.number))
return ID
}

74
utils/go-flags/main.go Normal file
View File

@@ -0,0 +1,74 @@
package main
import (
"fmt"
"github.com/jessevdk/go-flags"
)
func main() {
// Callback which will invoke callto:<argument> to call a number.
// Note that this works just on OS X (and probably only with
// Skype) but it shows the idea.
// opts.Call = func(num string) {
// cmd := exec.Command("open", "callto:"+num)
// cmd.Start()
// cmd.Process.Release()
// }
// Make some fake arguments to parse.
// args := []string{
// "-vv",
// "--offset=5",
// "-n", "Me",
// "-p", "3",
// "-s", "hello",
// "-s", "world",
// "--ptrslice", "hello",
// "--ptrslice", "world",
// "--intmap", "a:1",
// "--intmap", "b:5",
// "--filename", "hello.go",
// "id",
// "10",
// "remaining1",
// "remaining2",
// }
// Parse flags from `args'. Note that here we use flags.ParseArgs for
// the sake of making a working example. Normally, you would simply use
// flags.Parse(&opts) which uses os.Args
// _, err := flags.ParseArgs(&opts, args)
_, err := flags.Parse(&opts)
if err != nil {
panic(err)
}
fmt.Printf("Verbosity: %v\n", opts.Verbose)
fmt.Printf("Offset: %d\n", opts.Offset)
fmt.Printf("Name: %s\n", opts.Name)
// fmt.Printf("Ptr: %d\n", *opts.Ptr)
// fmt.Printf("StringSlice: %v\n", opts.StringSlice)
// fmt.Printf("PtrSlice: [%v %v]\n", *opts.PtrSlice[0], *opts.PtrSlice[1])
// fmt.Printf("IntMap: [a:%v b:%v]\n", opts.IntMap["a"], opts.IntMap["b"])
// fmt.Printf("Filename: %v\n", opts.Filename)
// fmt.Printf("Args.ID: %s\n", opts.Args.ID)
// fmt.Printf("Args.Num: %d\n", opts.Args.Num)
// fmt.Printf("Args.Rest: %v\n", opts.Args.Rest)
}
var opts struct {
// Slice of bool will append 'true' each time the option
// is encountered (can be set multiple times, like -vvv)
Verbose []bool `short:"v" long:"verbose" description:"Show verbose debug information"`
// Example of automatic marshalling to desired type (uint)
Offset uint `long:"offset" description:"Offset"`
// Example of a callback, called each time the option is found.
// Call func(string) `short:"c" description:"Call phone number"`
// Example of a required flag
Name string `short:"n" long:"name" description:"A name" required:"true" env:"ENV_NAME"`
}

View File

@@ -2,9 +2,8 @@ package log
import (
"fmt"
"testing"
"github.com/sirupsen/logrus"
"testing"
)
func TestSetting(t *testing.T) {