snowflake_sequencer.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package sequence
  2. import (
  3. "fmt"
  4. "hash/fnv"
  5. "github.com/bwmarrin/snowflake"
  6. "github.com/chrislusf/seaweedfs/weed/glog"
  7. )
  8. // a simple snowflake Sequencer
  9. type SnowflakeSequencer struct {
  10. node *snowflake.Node
  11. }
  12. func NewSnowflakeSequencer(nodeid string) (*SnowflakeSequencer, error) {
  13. nodeid_hash := hash(nodeid) & 0x3ff
  14. glog.V(0).Infof("use snowflake seq id generator, nodeid:%s hex_of_nodeid: %x", nodeid, nodeid_hash)
  15. node, err := snowflake.NewNode(int64(nodeid_hash))
  16. if err != nil {
  17. fmt.Println(err)
  18. return nil, err
  19. }
  20. sequencer := &SnowflakeSequencer{node: node}
  21. return sequencer, nil
  22. }
  23. func hash(s string) uint32 {
  24. h := fnv.New32a()
  25. h.Write([]byte(s))
  26. return h.Sum32()
  27. }
  28. func (m *SnowflakeSequencer) NextFileId(count uint64) uint64 {
  29. return uint64(m.node.Generate().Int64())
  30. }
  31. // ignore setmax as we are snowflake
  32. func (m *SnowflakeSequencer) SetMax(seenValue uint64) {
  33. }
  34. // return a new id as no Peek is stored
  35. func (m *SnowflakeSequencer) Peek() uint64 {
  36. return uint64(m.node.Generate().Int64())
  37. }