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 operation.go operation_string.go type_assert.go

Variables

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

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:

ctx, cancel := context.WithCancel(context.Background())
c := cache.New(provider(),
    mw.WithClearByContext(),
    cache.WithDataOption(cache.WithNamespace("clear_by_ctx", "")),
)

var cached, cached2 string

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(context.TODO(), 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(memory.WithEncoding(json.Encode, json.Decode)))

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: malformed: key is too long or contains invalid characters, value: ''
err: cache miss: memcache: cache miss, 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, value: ''
err: <nil>
err: <nil>, value: 'some redis value'

Code:

ctx := context.Background()
c := cache.New(provider(), mw.WithFallback(
    mw.CachesFallbackSuccess(func(ctx context.Context, d *cache.Item) error {
        fmt.Printf("loaded key: %#v\n", d.Key.Key)
        return cache.TypeAssert("some loaded data", d.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) 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) 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.

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 WithHandle Uses

func WithHandle(get, set, delete Handle) Configure

WithHandle sets get/set/delete handler.

func WithHandleCache Uses

func WithHandleCache(handlers ...func() (Operation, func(ctx context.Context, c *Cache, item *Item, next Init) error)) Configure

WithHandleCache add handler by cache operation type.

func WithHandleDelete Uses

func WithHandleDelete(h ...Handle) Configure

WithHandleDelete sets handlers delete.

func WithHandleGet Uses

func WithHandleGet(h ...Handle) Configure

WithHandleGet sets handlers get.

func WithHandleSet Uses

func WithHandleSet(h ...Handle) Configure

WithHandleSet sets handlers set.

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 error.

func (ErrorTarget) Error Uses

func (e ErrorTarget) Error() string

ErrorTarget errors.

type Handle Uses

type Handle func(ctx context.Context, item *Item, next Init) error

Handle middlewaare brfore/after init method.

type Init Uses

type Init func(ctx context.Context, item *Item) error

Init func for get/set/delete.

type Item Uses

type Item struct {
    Key   Key
    Value interface{}
    TTL   time.Duration
}

Item to get/set/delete in provider.

func NewItem Uses

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

NewItem creates new item and configure them for provider.

func (*Item) CopyTo Uses

func (i *Item) CopyTo(target *Item) error

CopyTo copy iyem to target.

func (*Item) Expired Uses

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

Expired gets expired time by ttl.

func (*Item) IsExpired Uses

func (i *Item) IsExpired() bool

IsExpired checks expired item.

func (*Item) Options Uses

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

Options gets item options.

func (*Item) TTLInSecond Uses

func (i *Item) TTLInSecond(in int64)

TTLInSecond sets ttl by seconds.

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 return prefix+separator+key for key.

type Operation Uses

type Operation int

Operation cache operation.

const (
    OperationGet    Operation = iota + 1 //get
    OperationSet                         //set
    OperationDelete                      //delete
)

available opearation.

func (Operation) String Uses

func (i Operation) String() string

type Option Uses

type Option func(*Item)

Option for get/set/delete methods.

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 interface {
    Delete(ctx context.Context, d *Item) error
    Get(ctx context.Context, d *Item) error
    Set(ctx context.Context, d *Item) error
}

Provider cache.

Directories

PathSynopsis
mw/prometheus

Package cache imports 6 packages (graph) and is imported by 1 packages. Updated 2020-05-26. Refresh now. Tools for package owners.