snowflake_sequencer.go 981 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. package sequence
  2. import (
  3. "fmt"
  4. "hash/fnv"
  5. "github.com/bwmarrin/snowflake"
  6. "github.com/seaweedfs/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. }