skiplist_element_store.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package redis3
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/go-redis/redis/v8"
  6. "github.com/seaweedfs/seaweedfs/weed/glog"
  7. "github.com/seaweedfs/seaweedfs/weed/util/skiplist"
  8. "google.golang.org/protobuf/proto"
  9. )
  10. type SkipListElementStore struct {
  11. Prefix string
  12. client redis.UniversalClient
  13. }
  14. var _ = skiplist.ListStore(&SkipListElementStore{})
  15. func newSkipListElementStore(prefix string, client redis.UniversalClient) *SkipListElementStore {
  16. return &SkipListElementStore{
  17. Prefix: prefix,
  18. client: client,
  19. }
  20. }
  21. func (m *SkipListElementStore) SaveElement(id int64, element *skiplist.SkipListElement) error {
  22. key := fmt.Sprintf("%s%d", m.Prefix, id)
  23. data, err := proto.Marshal(element)
  24. if err != nil {
  25. glog.Errorf("marshal %s: %v", key, err)
  26. }
  27. return m.client.Set(context.Background(), key, data, 0).Err()
  28. }
  29. func (m *SkipListElementStore) DeleteElement(id int64) error {
  30. key := fmt.Sprintf("%s%d", m.Prefix, id)
  31. return m.client.Del(context.Background(), key).Err()
  32. }
  33. func (m *SkipListElementStore) LoadElement(id int64) (*skiplist.SkipListElement, error) {
  34. key := fmt.Sprintf("%s%d", m.Prefix, id)
  35. data, err := m.client.Get(context.Background(), key).Result()
  36. if err != nil {
  37. if err == redis.Nil {
  38. return nil, nil
  39. }
  40. return nil, err
  41. }
  42. t := &skiplist.SkipListElement{}
  43. err = proto.Unmarshal([]byte(data), t)
  44. if err == nil {
  45. for i := 0; i < len(t.Next); i++ {
  46. if t.Next[i].IsNil() {
  47. t.Next[i] = nil
  48. }
  49. }
  50. if t.Prev.IsNil() {
  51. t.Prev = nil
  52. }
  53. }
  54. return t, err
  55. }