Back to godoc.org
gitoa.ru/go-4devs/cache

package cache

v0.1.0
Latest Go to latest
Published: May 17, 2020 | License: MIT | Module: gitoa.ru/go-4devs/cache

Index

Examples

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

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

TypeAssert assert source to target.

type Cache

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

Cache base cache.

Example (ClearByContext)

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: ''
Example (ClearByTTL)

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: ''
Example (Encoding)

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'
Example (Lru)

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>
Example (Map)

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'
Example (Memacache)

Code:

ctx := context.Background()
c := cache.New(memcache.New(test.MemcacheCient()), 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'
Example (Redis)

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'
Example (WithFallback)

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'
Example (WithMetrics)

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
Example (WithNamespace)

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

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

New creates new cache by provider.

func (*Cache) Delete

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

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

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

type Configure func(*Cache)

Configure configure cache.

func WithDataOption

func WithDataOption(do ...Option) Configure

WithDataOption sets cache default data options.

func WithHandle

func WithHandle(get, set, delete Handle) Configure

WithHandle sets get/set/delete handler.

func WithHandleCache

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

func WithHandleDelete

func WithHandleDelete(h ...Handle) Configure

WithHandleDelete sets handlers delete.

func WithHandleGet

func WithHandleGet(h ...Handle) Configure

WithHandleGet sets handlers get.

func WithHandleSet

func WithHandleSet(h ...Handle) Configure

WithHandleSet sets handlers set.

type ErrorTarget

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

ErrorTarget errs target is not a settable.

func NewErrorTarget

func NewErrorTarget(target interface{}) ErrorTarget

NewErrorTarget creates new error.

func (ErrorTarget) Error

func (e ErrorTarget) Error() string

ErrorTarget errors.

type Handle

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

Handle middlewaare brfore/after init method.

type Init

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

Init func for get/set/delete.

type Item

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

Item to get/set/delete in provider.

func NewItem

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

NewItem creates new item and configure them for provider.

func (*Item) CopyTo

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

func (*Item) Expired

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

Expired gets expired time by ttl.

func (*Item) IsExpired

func (i *Item) IsExpired() bool

IsExpired checks expired item.

func (*Item) Options

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

func (*Item) TTLInSecond

func (i *Item) TTLInSecond(in int64)

TTLInSecond sets ttl by seconds.

type Key

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

Key with prefix and separator.

func (Key) String

func (k Key) String() string

String return prefix+separator+key for key.

type Operation

type Operation int

Operation cache operation.

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

available opearation.

func (Operation) String

func (i Operation) String() string

type Option

type Option func(*Item)

Option for get/set/delete methods.

func WithNamespace

func WithNamespace(prefix, sep string) Option

WithNamespace sets prefix and separator.

func WithTTL

func WithTTL(ttl time.Duration) Option

WithTTL sets ttl.

type Provider

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.

Documentation was rendered with GOOS=linux and GOARCH=amd64.

Jump to identifier

Keyboard shortcuts

? : This menu
f or F : Jump to identifier