goburrow / cache

Mango Cache 🥭 - Partial implementation of Guava Cache in Go (golang).
BSD 3-Clause "New" or "Revised" License
574 stars 48 forks source link

Allow to change parameters of the cache #30

Closed seblaz closed 2 years ago

seblaz commented 2 years ago

Hi! It would be great if some properties of the cache could be changed after the creation, like the MaximumSize and ExpireAfterWrite, is that possible?

nqv commented 2 years ago

it isn't supported, cache properties are immutable.

juvenn commented 2 years ago

Hi @nqv , I can concur with @seblaz .

In our use case, we have a common util to build the default cache, then allow others to customize with options.

func BuildResilientLoadingCache(loadfn cache.LoaderFunc, maxSize int, writeExpire time.Duration,
    opts ...cache.Option) cache.LoadingCache {
    options := append([]cache.Option{
        cache.WithPolicy("tinylfu"),
        cache.WithReloader(&ResilientReloader{Load: loadfn}),
        cache.WithMaximumSize(maxSize),
        cache.WithRefreshAfterWrite(writeExpire),
    }, opts...)
    c := cache.NewLoadingCache(
        loadfn,
        options...,
    )
    return c
}

But if we allow applying options to cache,

func BuildResilientLoadingCache(loadfn cache.LoaderFunc, maxSize int, writeExpire time.Duration,
    opts ...cache.Option) cache.LoadingCache {
    c := cache.NewLoadingCache(
        loadfn,
        cache.WithPolicy("tinylfu"),
        cache.WithReloader(&ResilientReloader{Load: loadfn}),
        cache.WithMaximumSize(maxSize),
        cache.WithRefreshAfterWrite(writeExpire),
    )
        for _, opt := range opts {
               opt(c)
        }
    return c
}

user can choose to further extend the cache with customized options if desirable.