2021-03-25 10:49:26 +00:00
|
|
|
package sequence
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"hash/fnv"
|
|
|
|
|
|
|
|
"github.com/bwmarrin/snowflake"
|
2021-03-25 10:59:40 +00:00
|
|
|
"github.com/chrislusf/seaweedfs/weed/glog"
|
2021-03-25 10:49:26 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// a simple snowflake Sequencer
|
|
|
|
type SnowflakeSequencer struct {
|
|
|
|
node *snowflake.Node
|
|
|
|
}
|
|
|
|
|
2021-07-24 03:54:03 +00:00
|
|
|
func NewSnowflakeSequencer(nodeid string, snowflakeId int) (*SnowflakeSequencer, error) {
|
2021-03-25 10:59:40 +00:00
|
|
|
nodeid_hash := hash(nodeid) & 0x3ff
|
2021-07-24 03:54:03 +00:00
|
|
|
if snowflakeId != 0 {
|
|
|
|
nodeid_hash = uint32(snowflakeId)
|
|
|
|
}
|
2021-04-03 18:37:13 +00:00
|
|
|
glog.V(0).Infof("use snowflake seq id generator, nodeid:%s hex_of_nodeid: %x", nodeid, nodeid_hash)
|
2021-03-25 10:59:40 +00:00
|
|
|
node, err := snowflake.NewNode(int64(nodeid_hash))
|
2021-03-25 10:49:26 +00:00
|
|
|
if err != nil {
|
|
|
|
fmt.Println(err)
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
sequencer := &SnowflakeSequencer{node: node}
|
|
|
|
return sequencer, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func hash(s string) uint32 {
|
|
|
|
h := fnv.New32a()
|
|
|
|
h.Write([]byte(s))
|
|
|
|
return h.Sum32()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *SnowflakeSequencer) NextFileId(count uint64) uint64 {
|
|
|
|
return uint64(m.node.Generate().Int64())
|
|
|
|
}
|
|
|
|
|
|
|
|
// ignore setmax as we are snowflake
|
|
|
|
func (m *SnowflakeSequencer) SetMax(seenValue uint64) {
|
|
|
|
}
|
|
|
|
|
|
|
|
// return a new id as no Peek is stored
|
|
|
|
func (m *SnowflakeSequencer) Peek() uint64 {
|
|
|
|
return uint64(m.node.Generate().Int64())
|
|
|
|
}
|