cacheAside

package module
v0.0.0-...-6f11c88 Latest Latest
Warning

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

Go to latest
Published: Jun 16, 2023 License: MIT Imports: 9 Imported by: 0

README

cacheAside

Go codecov Release Go Report Card Go Reference

Description

cacheAside is a generic cache-aside implementation

Example use:
package main

import (
	"fmt"
	
	"github.com/me-cs/cacheAside"
)

type UserInfo struct {
	Id   string
	Name string
}

func init() {
	cacheAside.Init(nil)
}

// your db fetch method

func DbUserInfo(id string) (*UserInfo, bool, error) {
	return &UserInfo{
		Id:   "1",
		Name: "tom",
	}, false, nil
}

// warp your dao fetch method

func DaoUserInfo(id string) (*UserInfo, error) {
	return cacheAside.Get(id, DbUserInfo)
}

// fetch user info in business code
func main() {
	u, err := DaoUserInfo("1")
	if err != nil {
		fmt.Println(err)
	}
	fmt.Printf("%+v\n", u)
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	//ErrNotFound is the error returned when the key is not found in cache and db
	ErrNotFound = errors.New("not found")
)

Functions

func Delete

func Delete(k ...string)

Delete deletes the key from cache

func Get

func Get[T any](key string, dbFetch func(string) (T, bool, error)) (res T, err error)

Get gets the value from cache, if not found, fetch from db then add to cache

func Init

func Init(opt *Option)

Init initializes the cache aside instance

func MultiGet

func MultiGet[T any](keys []string, dbFetch func(id []string) (map[string]T, error)) (res map[string]T, err error)

MultiGet gets the values from cache, if not found, fetch from db then add to cache

Types

type Option

type Option struct {
	// BatchSize is the number of keys to be fetched from db in one batch
	BatchSize int
	// DefaultCacheExpire is the default expire time of cache
	DefaultCacheExpire time.Duration
	// MissCacheExpire is the default expire time of miss cache
	MissCacheExpire time.Duration
	// CleanInterval is the default clean interval of cache
	CleanInterval time.Duration
}

Option is the option of cache aside

type Unstable

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

An Unstable is used to generate random value around the mean value base on given deviation.

func NewUnstable

func NewUnstable(deviation float64) Unstable

NewUnstable returns an Unstable.

func (Unstable) AroundDuration

func (u Unstable) AroundDuration(base time.Duration) time.Duration

AroundDuration returns a random duration with given base and deviation.

Jump to

Keyboard shortcuts

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