singleflight

package module
v0.0.0-...-f8e9dc7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 25, 2024 License: BSD-3-Clause Imports: 10 Imported by: 0

Documentation

Index

Examples

Constants

View Source
const OK = "ok"

Variables

View Source
var (
	ErrTimeout            = errors.New("group: timeout waiting for result")
	ErrSubscriptionClosed = errors.New("group: subscription closed")
)

Functions

This section is empty.

Types

type BackOff

type BackOff interface {
	Duration(i int) time.Duration
}

type Cache

type Cache[T any] struct {
	Client  *redis.Client
	Group   *Group
	LockTTL time.Duration
	WaitTTL time.Duration
	Suffix  string
}
Example
// Cache example.
// When the cache is stale, only once worker will populate
// the cache, and the rest will wait.

stop := redistest.Init()
defer stop()

client := redis.NewClient(&redis.Options{
	Addr: redistest.Addr(),
})
defer client.Close()

cache := singleflight.NewCache[string](client)
ctx := context.Background()

hit := new(atomic.Int64)
exec := new(atomic.Int64)

n := 10
var wg sync.WaitGroup
wg.Add(n)

for range n {
	go func() {
		defer wg.Done()
		v, hitOrMiss, err := cache.LoadOrStore(ctx, "foo", func(context.Context) (string, error) {
			exec.Add(1)
			return "bar", nil
		}, 10*time.Second)
		if err != nil {
			panic(err)
		}
		if v != "bar" {
			panic("unexpected value: " + v)
		}
		if hitOrMiss {
			hit.Add(1)
		}

	}()
}
wg.Wait()

fmt.Println("hit:", hit.Load())
fmt.Println("exec:", exec.Load())
Output:

hit: 9
exec: 1

func NewCache

func NewCache[T any](client *redis.Client) *Cache[T]

func (*Cache[T]) LoadOrStore

func (c *Cache[T]) LoadOrStore(ctx context.Context, key string, getter func(ctx context.Context) (T, error), ttl time.Duration) (T, bool, error)

type ExponentialBackOff

type ExponentialBackOff struct {
	Base time.Duration
	Cap  time.Duration
}

func NewExponentialBackOff

func NewExponentialBackOff(base, cap time.Duration) *ExponentialBackOff

func (*ExponentialBackOff) Duration

func (b *ExponentialBackOff) Duration(i int) time.Duration

type Group

type Group struct {
	BackOff BackOff
	Client  *redis.Client
	Locker  *lock.Locker
	Group   *singleflight.Group[bool]
}

func New

func New(client *redis.Client) *Group

func (*Group) Do

func (g *Group) Do(ctx context.Context, key string, fn func(context.Context) error, lockTTL, waitTTL time.Duration) (doOrWait bool, err error)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL