snowflake_sequencer.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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, snowflakeId int) (*SnowflakeSequencer, error) {
  13. nodeid_hash := hash(nodeid) & 0x3ff
  14. if snowflakeId != 0 {
  15. nodeid_hash = uint32(snowflakeId)
  16. }
  17. glog.V(0).Infof("use snowflake seq id generator, nodeid:%s hex_of_nodeid: %x", nodeid, nodeid_hash)
  18. node, err := snowflake.NewNode(int64(nodeid_hash))
  19. if err != nil {
  20. fmt.Println(err)
  21. return nil, err
  22. }
  23. sequencer := &SnowflakeSequencer{node: node}
  24. return sequencer, nil
  25. }
  26. func hash(s string) uint32 {
  27. h := fnv.New32a()
  28. h.Write([]byte(s))
  29. return h.Sum32()
  30. }
  31. func (m *SnowflakeSequencer) NextFileId(count uint64) uint64 {
  32. return uint64(m.node.Generate().Int64())
  33. }
  34. // ignore setmax as we are snowflake
  35. func (m *SnowflakeSequencer) SetMax(seenValue uint64) {
  36. }
  37. // return a new id as no Peek is stored
  38. func (m *SnowflakeSequencer) Peek() uint64 {
  39. return uint64(m.node.Generate().Int64())
  40. }