2021-10-04 08:01:31 +00:00
|
|
|
package redis3
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
2023-06-13 05:27:38 +00:00
|
|
|
"github.com/go-redis/redis/v8"
|
2022-07-29 07:17:28 +00:00
|
|
|
"github.com/seaweedfs/seaweedfs/weed/glog"
|
|
|
|
"github.com/seaweedfs/seaweedfs/weed/util/skiplist"
|
2022-08-17 19:05:07 +00:00
|
|
|
"google.golang.org/protobuf/proto"
|
2021-10-04 08:01:31 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type SkipListElementStore struct {
|
2021-10-07 01:18:24 +00:00
|
|
|
Prefix string
|
2021-10-04 08:01:31 +00:00
|
|
|
client redis.UniversalClient
|
|
|
|
}
|
|
|
|
|
|
|
|
var _ = skiplist.ListStore(&SkipListElementStore{})
|
|
|
|
|
|
|
|
func newSkipListElementStore(prefix string, client redis.UniversalClient) *SkipListElementStore {
|
|
|
|
return &SkipListElementStore{
|
2021-10-07 01:18:24 +00:00
|
|
|
Prefix: prefix,
|
2021-10-04 08:01:31 +00:00
|
|
|
client: client,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *SkipListElementStore) SaveElement(id int64, element *skiplist.SkipListElement) error {
|
2021-10-07 01:18:24 +00:00
|
|
|
key := fmt.Sprintf("%s%d", m.Prefix, id)
|
2021-10-04 08:01:31 +00:00
|
|
|
data, err := proto.Marshal(element)
|
|
|
|
if err != nil {
|
|
|
|
glog.Errorf("marshal %s: %v", key, err)
|
|
|
|
}
|
|
|
|
return m.client.Set(context.Background(), key, data, 0).Err()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *SkipListElementStore) DeleteElement(id int64) error {
|
2021-10-07 01:18:24 +00:00
|
|
|
key := fmt.Sprintf("%s%d", m.Prefix, id)
|
2021-10-04 08:01:31 +00:00
|
|
|
return m.client.Del(context.Background(), key).Err()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *SkipListElementStore) LoadElement(id int64) (*skiplist.SkipListElement, error) {
|
2021-10-07 01:18:24 +00:00
|
|
|
key := fmt.Sprintf("%s%d", m.Prefix, id)
|
2021-10-04 08:01:31 +00:00
|
|
|
data, err := m.client.Get(context.Background(), key).Result()
|
|
|
|
if err != nil {
|
|
|
|
if err == redis.Nil {
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
t := &skiplist.SkipListElement{}
|
|
|
|
err = proto.Unmarshal([]byte(data), t)
|
2021-10-04 09:31:38 +00:00
|
|
|
if err == nil {
|
2021-10-08 04:13:31 +00:00
|
|
|
for i := 0; i < len(t.Next); i++ {
|
2021-10-04 09:31:38 +00:00
|
|
|
if t.Next[i].IsNil() {
|
|
|
|
t.Next[i] = nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if t.Prev.IsNil() {
|
|
|
|
t.Prev = nil
|
|
|
|
}
|
|
|
|
}
|
2021-10-04 08:01:31 +00:00
|
|
|
return t, err
|
|
|
|
}
|