cache: gitoa.ru/go-4devs/cache Index | Examples | Files | Directories

package cache

import "gitoa.ru/go-4devs/cache"

Index

Examples

Package Files

cache.go error.go item.go operation.go provider.go type_assert.go

Constants

const (
    OperationGet    = "get"
    OperationSet    = "set"
    OperationDelete = "delete"
)

available operation.

Variables

var (
    ErrCacheMiss          = errors.New("cache miss")
    ErrCacheExpired       = errors.New("cache expired")
    ErrSourceNotValid     = errors.New("source is not valid")
    ErrKeyNotValid        = errors.New("key is not valid")
    ErrTargetNil          = errors.New("target is nil")
    ErrOperationNotAllwed = errors.New("operation not allowed")
)

Cached errors.

func TypeAssert Uses

func TypeAssert(source, target interface{}) (err error)

TypeAssert assert source to target.

type Cache Uses

type Cache struct {
    // contains filtered or unexported fields
}

Cache base cache.

Code:

type ctxKey int

var (
    requestID       ctxKey = 1
    cached, cached2 string
)

ctx, cancel := context.WithCancel(context.WithValue(context.Background(), requestID, "unique ctx key"))
ctx2 := context.WithValue(context.Background(), requestID, "unique ctx key2")
c := cache.New(provider(),
    mw.WithClearByContext(requestID),
    cache.WithDataOption(cache.WithNamespace("clear_by_ctx", "")),
)

fmt.Printf("err: %v\n", c.Set(ctx, 1, "some ctx loaded data", cache.WithTTL(time.Hour)))
fmt.Printf("err: %v, value: '%v'\n", c.Get(ctx, 1, &cached), cached)
cancel()
time.Sleep(time.Millisecond)
fmt.Printf("err: %v, value: '%v'\n", c.Get(ctx2, 1, &cached2), cached2)

Output:

err: <nil>
err: <nil>, value: 'some ctx loaded data'
err: cache miss: map, value: ''

Code:

ctx := context.Background()
c := cache.New(provider(),
    mw.WithClearByTTL(),
    cache.WithDataOption(cache.WithNamespace("clear_by_ttl", "")),
)

var cached, cached2 string

fmt.Printf("err: %v\n", c.Set(ctx, 1, "some ttl loaded data", cache.WithTTL(time.Microsecond*200)))
fmt.Printf("err: %v, value: '%v'\n", c.Get(ctx, 1, &cached), cached)
time.Sleep(time.Second)
fmt.Printf("err: %v, value: '%v'\n", c.Get(ctx, 1, &cached2), cached2)

Output:

err: <nil>
err: <nil>, value: 'some ttl loaded data'
err: cache miss: map, value: ''

Code:

ctx := context.Background()
c := cache.New(memory.NewEncoding(), cache.WithDataOption(cache.WithMarshal(gob.Unmarshal, gob.Marshal)))

var cached string

fmt.Printf("err: %v, value: '%v'\n", c.Get(ctx, "not found key", &cached), cached)
fmt.Printf("err: %v\n", c.Set(ctx, "key", "some value"))
fmt.Printf("err: %v, value: '%v'\n", c.Get(ctx, "key", &cached), cached)

Output:

err: cache miss: encoding, value: ''
err: <nil>
err: <nil>, value: 'some value'

Code:

ctx := context.Background()
client, _ := glru.New(10)

c := cache.New(lru.New(client), cache.WithDataOption(cache.WithTTL(time.Hour)))

var cached string

fmt.Printf("err: %v, value: '%v'\n", c.Get(ctx, "not found lru key", &cached), cached)
fmt.Printf("err: %v\n", c.Set(ctx, "key", "some lru value"))
fmt.Printf("err: %v, value: '%v'\n", c.Get(ctx, "key", &cached), cached)
fmt.Printf("deleted err: %v\n", c.Delete(ctx, "key"))

Output:

err: cache miss: lru, value: ''
err: <nil>
err: <nil>, value: 'some lru value'
deleted err: <nil>

Code:

ctx := context.Background()
c := cache.New(memory.NewMap())

var cached string

fmt.Printf("err: %v, value: '%v'\n", c.Get(ctx, "not found key", &cached), cached)
fmt.Printf("err: %v\n", c.Set(ctx, "key", "some value"))
fmt.Printf("err: %v, value: '%v'\n", c.Get(ctx, "key", &cached), cached)

Output:

err: cache miss: map, value: ''
err: <nil>
err: <nil>, value: 'some value'

Code:

ctx := context.Background()
c := cache.New(memcache.New(test.MemcacheClient()), cache.WithDataOption(cache.WithNamespace("memcache", ":")))

var cached string

fmt.Printf("err: %v, value: '%v'\n", c.Get(ctx, "not found memcached key", &cached), cached)
fmt.Printf("err: %v, value: '%v'\n", c.Get(ctx, "not:found:memcached:key", &cached), cached)
fmt.Printf("err: %v\n", c.Set(ctx, "key", "some mamcache value"))
fmt.Printf("err: %v, value: '%v'\n", c.Get(ctx, "key", &cached), cached)

Output:

err: key is not valid: memcache, value: ''
err: cache miss: memcache, value: ''
err: <nil>
err: <nil>, value: 'some mamcache value'

Code:

ctx := context.Background()
c := cache.New(redis.New(test.RedisClient()))

var cached string

fmt.Printf("err: %v, value: '%v'\n", c.Get(ctx, "not found redis key", &cached), cached)
fmt.Printf("err: %v\n", c.Set(ctx, "key", "some redis value", cache.WithNamespace("redis", ":")))
fmt.Printf("err: %v, value: '%v'\n", c.Get(ctx, "redis:key", &cached), cached)

Output:

err: cache miss: redis pool, value: ''
err: <nil>
err: <nil>, value: 'some redis value'

Code:

ctx := context.Background()
c := cache.New(provider(), mw.WithFallback(
    func(ctx context.Context, key, value interface{}) error {
        fmt.Printf("loaded key: %#v\n", key)

        return cache.TypeAssert("some loaded data", value)
    },
    func(i *cache.Item, e error) bool {
        return e != nil
    },
))

var cached, cached2 string

fmt.Printf("err: %v, value: '%v'\n", c.Get(ctx, 1, &cached), cached)
fmt.Printf("err: %v, value: '%v'\n", c.Get(ctx, 1, &cached2), cached2)

Output:

loaded key: 1
err: <nil>, value: 'some loaded data'
err: <nil>, value: 'some loaded data'

Code:

ctx := context.Background()
cacheLabel := "cache_label"
c := cache.New(provider(),
    mw.WithMetrics(prometheus.Metrics{}, mw.LabelName(cacheLabel)),
    cache.WithDataOption(cache.WithNamespace("metrics", ":")),
)

var cached, cached2 string

fmt.Printf("err: %v, value: '%v'\n", c.Get(ctx, 1, &cached), cached)
fmt.Printf("err: %v\n", c.Set(ctx, 1, "cached"))
fmt.Printf("err: %v, value: '%v'\n", c.Get(ctx, 1, &cached2), cached2)

mfs, _ := prom.DefaultGatherer.Gather()
for _, mf := range mfs {
    for _, metric := range mf.GetMetric() {
        label := metric.GetLabel()
        if len(label) > 0 && metric.Counter != nil {
            fmt.Printf("name:%s, label:%s, value: %.0f\n", *mf.Name, *label[0].Value, mf.GetMetric()[0].Counter.GetValue())
        }
    }
}

Output:

err: cache miss: map, value: ''
err: <nil>
err: <nil>, value: 'cached'
name:cache_hit_total, label:cache_label, value: 1
name:cache_miss_total, label:cache_label, value: 1

Code:

ctx := context.Background()
c := cache.New(provider(), cache.WithDataOption(
    cache.WithNamespace("prefix", ":"),
    cache.WithTTL(time.Hour),
))

var cached, cached2 string

fmt.Printf("prefix  err: %v, value: '%v'\n", c.Get(ctx, "key", &cached), cached)
fmt.Printf("prefix  err: %v\n", c.Set(ctx, "key", "some value", cache.WithTTL(time.Minute)))
fmt.Printf("prefix2 err: %v\n", c.Set(ctx, "key", "some value2", cache.WithNamespace("prefix2", ":")))
fmt.Printf("prefix  err: %v, value: '%v'\n", c.Get(ctx, "key", &cached), cached)
fmt.Printf("prefix2 err: %v, value: '%v'\n", c.Get(ctx, "key", &cached2, cache.WithNamespace("prefix2", ":")), cached2)

Output:

prefix  err: cache miss: map, value: ''
prefix  err: <nil>
prefix2 err: <nil>
prefix  err: <nil>, value: 'some value'
prefix2 err: <nil>, value: 'some value2'

func New Uses

func New(prov Provider, opts ...Configure) *Cache

New creates new cache by provider.

func (*Cache) Delete Uses

func (c *Cache) Delete(ctx context.Context, key interface{}, opts ...Option) error

Delete handles middlewares and delete value by key and options.

func (*Cache) Execute Uses

func (c *Cache) Execute(ctx context.Context, operation string, key, value interface{}, opts ...Option) error

func (*Cache) Get Uses

func (c *Cache) Get(ctx context.Context, key, value interface{}, opts ...Option) error

Get handles middlewares and gets value by key and options.

func (*Cache) Item Uses

func (c *Cache) Item(key, value interface{}, opts ...Option) *Item

func (*Cache) Set Uses

func (c *Cache) Set(ctx context.Context, key, value interface{}, opts ...Option) error

Set handles middlewares and sets value by key and options.

func (*Cache) With Uses

func (c *Cache) With(opts ...Configure) *Cache

type Configure Uses

type Configure func(*Cache)

Configure configure cache.

func WithDataOption Uses

func WithDataOption(do ...Option) Configure

WithDataOption sets cache default data options.

func WithDefaultNamespace Uses

func WithDefaultNamespace(ns, separator string) Configure

WithDefaultNamespace sets cache default namespace.

func WithDefaultTTL Uses

func WithDefaultTTL(ttl time.Duration) Configure

WithDefaultTTL sets cache default ttl.

func WithHandleDelete Uses

func WithHandleDelete(m ...Handle) Configure

WithHandleDelete add a handler for the delete operation.

func WithHandleGet Uses

func WithHandleGet(m ...Handle) Configure

WithHandleGet add a handler for the get operation.

func WithHandleOperation Uses

func WithHandleOperation(op string, m ...Handle) Configure

WithHandleOperation add a handler for the operation.

func WithHandleSet Uses

func WithHandleSet(m ...Handle) Configure

WithHandleSet add a handler for the set operation.

func WithMiddleware Uses

func WithMiddleware(mw ...Handle) Configure

WithMiddleware sets middleware to provider.

type ErrorTarget Uses

type ErrorTarget struct {
    // contains filtered or unexported fields
}

ErrorTarget errs target is not a settable.

func NewErrorTarget Uses

func NewErrorTarget(target interface{}) ErrorTarget

NewErrorTarget creates new target error.

func (ErrorTarget) Error Uses

func (e ErrorTarget) Error() string

ErrorTarget errors.

type Handle Uses

type Handle func(ctx context.Context, operation string, item *Item, next Provider) error

Handle middleware before/after provider.

func ChainHandle Uses

func ChainHandle(handle ...Handle) Handle

ChainHandle chain handle middleware.

type Item Uses

type Item struct {
    Key   Key
    Value interface{}
    TTL   time.Duration
    // contains filtered or unexported fields
}

Item to pass to the provider.

func NewItem Uses

func NewItem(key, value interface{}, opts ...Option) *Item

NewItem creates and configure new item.

func (*Item) Expired Uses

func (i *Item) Expired() time.Time

Expired get the time when the ttl is outdated.

func (*Item) IsExpired Uses

func (i *Item) IsExpired() bool

IsExpired checks expired item.

func (*Item) Marshal Uses

func (i *Item) Marshal() ([]byte, error)

func (*Item) Options Uses

func (i *Item) Options() []Option

Options gets item options.

func (*Item) TTLInSecond Uses

func (i *Item) TTLInSecond(in int64)

TTLInSecond to set the ttl in seconds.

func (*Item) Unmarshal Uses

func (i *Item) Unmarshal(data []byte) error

func (*Item) With Uses

func (i *Item) With(key, val interface{}, opts ...Option) *Item

type Key Uses

type Key struct {
    Key       interface{}
    Prefix    string
    Separator string
}

Key with prefix and separator.

func (Key) String Uses

func (k Key) String() string

String returns a formatted key.

func (Key) Value Uses

func (k Key) Value() interface{}

type Option Uses

type Option func(*Item)

Option ffor the configuration item.

func WithMarshal Uses

func WithMarshal(unmarshal encoding.Unmarshal, marshal encoding.Marshal) Option

WithMarshal sets marshal and unmarshal.

func WithNamespace Uses

func WithNamespace(prefix, sep string) Option

WithNamespace sets prefix and separator.

func WithTTL Uses

func WithTTL(ttl time.Duration) Option

WithTTL sets ttl.

type Provider Uses

type Provider func(ctx context.Context, operation string, item *Item) error

Provider for different types of cache, in memory, lru, redis.

func OperationProvider Uses

func OperationProvider(prov map[string]func(ctx context.Context, item *Item) error) Provider

OperationProvider creating a provider based on available operations.

Directories

PathSynopsis
item
mw
mw/prometheus
provider/lru
provider/memcache
provider/memory
provider/pebble
provider/redis
provider/ristretto
test

Package cache imports 8 packages (graph) and is imported by 9 packages. Updated 2020-09-30. Refresh now. Tools for package owners.