lab2
This commit is contained in:
+79
@@ -0,0 +1,79 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"golang.org/x/sync/singleflight"
|
||||
)
|
||||
|
||||
type SingleflightCache struct {
|
||||
cache Cache
|
||||
group singleflight.Group
|
||||
}
|
||||
|
||||
func WithSingleflight(cache Cache) *SingleflightCache {
|
||||
return &SingleflightCache{cache: cache}
|
||||
}
|
||||
|
||||
func (s *SingleflightCache) GetOrLoad(
|
||||
ctx context.Context,
|
||||
key string,
|
||||
ttl time.Duration,
|
||||
loader func(ctx context.Context) ([]byte, error),
|
||||
) ([]byte, error) {
|
||||
value, err := s.cache.Get(ctx, key)
|
||||
if err == nil {
|
||||
return value, nil
|
||||
}
|
||||
|
||||
if !errors.Is(err, ErrCacheMiss) {
|
||||
return loader(ctx)
|
||||
}
|
||||
|
||||
result, err, _ := s.group.Do(key, func() (any, error) {
|
||||
loadCtx := context.WithoutCancel(ctx)
|
||||
if cached, err := s.cache.Get(loadCtx, key); err == nil {
|
||||
return cached, nil
|
||||
}
|
||||
loaded, loadErr := loader(loadCtx)
|
||||
if loadErr != nil {
|
||||
return nil, loadErr
|
||||
}
|
||||
|
||||
_ = s.cache.Set(loadCtx, key, loaded, ttl)
|
||||
|
||||
return loaded, nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
loaded, ok := result.([]byte)
|
||||
if !ok {
|
||||
return nil, errors.New("cache: unexpected singleflight result")
|
||||
}
|
||||
|
||||
return loaded, nil
|
||||
}
|
||||
|
||||
func (s *SingleflightCache) Get(ctx context.Context, key string) ([]byte, error) {
|
||||
return s.cache.Get(ctx, key)
|
||||
}
|
||||
|
||||
func (s *SingleflightCache) Set(ctx context.Context, key string, value []byte, ttl time.Duration) error {
|
||||
return s.cache.Set(ctx, key, value, ttl)
|
||||
}
|
||||
|
||||
func (s *SingleflightCache) Delete(ctx context.Context, keys ...string) error {
|
||||
return s.cache.Delete(ctx, keys...)
|
||||
}
|
||||
|
||||
func (s *SingleflightCache) Ping(ctx context.Context) error {
|
||||
return s.cache.Ping(ctx)
|
||||
}
|
||||
|
||||
func (s *SingleflightCache) Close() error {
|
||||
return s.cache.Close()
|
||||
}
|
||||
Reference in New Issue
Block a user