cache

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jan 13, 2025 License: MIT Imports: 4 Imported by: 0

README

cache

Simple cache with using different libraries.

go get github.com/worldline-go/cache

Usage

c := cache.New(context.Background(), cache.WithTTL(10*time.Second), cache.WithMaxSize(1000))

priceCache, err := cache.Port[string, int](c)
// ...

priceCache.Set("key", 100)
v, ok, err := vcache.Get("key")

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrInvalidType = errors.New("invalid type")

Functions

This section is empty.

Types

type Cache

type Cache struct {
	// contains filtered or unexported fields
}
Example
package main

import (
	"context"
	"fmt"
	"time"

	"github.com/worldline-go/cache"
)

func main() {
	cfg := cache.Config{
		MaxItems: 1_000,
		TTL:      30 * time.Minute,
	}

	c := cache.New(context.Background(), cfg.ToOption())

	vcache, err := cache.Port[string, int](c)
	if err != nil {
		panic(err)
	}

	if err := vcache.Set("key", 42); err != nil {
		panic(err)
	}

	v, ok, err := vcache.Get("key")
	if err != nil {
		panic(err)
	}

	if !ok {
		panic("key not found")
	}

	fmt.Println(v)
}
Output:
42

func New

func New(_ context.Context, opts ...Option) *Cache

type Cacher

type Cacher[K comparable, V any] interface {
	Get(key K) (V, bool, error)
	Set(key K, value V) error
}

func Port

func Port[K comparable, V any](c *Cache) (Cacher[K, V], error)

type Config

type Config struct {
	// The maximum number of items the cache can hold.
	MaxItems int `cfg:"max_items" json:"max_items"`
	// TTL is the time to live for each item in the cache.
	TTL time.Duration `cfg:"ttl" json:"ttl"`
}

func (*Config) SetDefault

func (c *Config) SetDefault(maxItems int, ttl time.Duration)

func (*Config) ToOption

func (c *Config) ToOption() Option

type Option

type Option func(*option)

func WithMaxItems

func WithMaxItems(maxItems int) Option

WithMaxItems sets the maximum number of items the cache can hold.

func WithTTL

func WithTTL(ttl time.Duration) Option

WithTTL sets the time to live for each item in the cache.

func WithTypeStorage

func WithTypeStorage(t Type) Option

WithTypeStorage sets the type of cache to use.

type Type

type Type int
const (
	TypeMemory Type = iota
)

Directories

Path Synopsis
plugins

Jump to

Keyboard shortcuts

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