newcache

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Sep 14, 2021 License: MIT Imports: 5 Imported by: 0

README

NewCache

Latest Release GoDoc

Golang cache lib, easy to register your cache flush daemon.

Installation

To install new-cache, simply run:

go get github.com/newtorn/new-cache

To compile it from source:

cd $GOPATH/src/github.com/newtorn/new-cache
go get -u -v
go build && go test -v

Example

Get Started
package main

import (
	"fmt"
	"time"

	"github.com/newtorn/new-cache"
)

// User represents a data entity, we can store into the cache.
type User struct {
	Username string
	Password string
}

func main() {
	// Call Singleton for the first time will create cache.
	cache := newcache.Singleton()

	// We will put a new item in the cache. It will expire after
	// not being accessed via SetEx(key) for more than 5 seconds.
	user := User{Username: "Jack", Password: "123456"}
	cache.SetEx(user.Username, &user, 5*time.Second)

	// Let's retrieve the item from the cache.
	val, ok := cache.Get(user.Username)
	if ok {
		fmt.Println("Found value in cache:", val)
	} else {
		fmt.Println("Not found retrieving value from cache")
	}

	// Wait for the item to expire in cache.
	time.Sleep(6 * time.Second)
	val, ok = cache.Get(user.Username)
	if !ok {
		fmt.Println("Item is not cached (anymore).")
	}

	// Set another item that never expires.
	cache.SetEx(user.Username, &user, 0)

	// Set another item that with default expiration.
	cache.Set(user.Username, &user)

	// Remove the item from the cache.
	cache.Del("someKey")

	// Wipe the entire cache table.
	cache.Flush()
}

To run this example, go to examples/get-started/ and run:

go run main.go
Cache Register Flush Daemon
package main

import (
	"context"
	"fmt"
	"time"

	cache "github.com/newtorn/new-cache"
)

// User represents a data entity, we can store into cache.
type User struct {
	Username string
	Password string
}

// userService implements a CacheFLushDaemon for cache registering.
type userService struct {
	users []*User
	done  chan interface{}
}

func (us *userService) Done(ctx context.Context) (done <-chan interface{}) {
	return us.done
}

func (us *userService) LoadKeys(ctx context.Context, value interface{}) []string {
	return []string{
		value.(*User).Username,
	}
}

func (us *userService) LoadValues(ctx context.Context) []interface{} {
	values := make([]interface{}, len(us.users))
	for i := 0; i < len(us.users); i++ {
		values[i] = us.users[i]
	}
	return values
}

func main() {
	ctx := context.Background()
	// Only init once new-cache configuration, must be called before singleton and register.
	// cache.InitOnce(cache.CacheConfig{})
	cache.InitOnce(cache.CacheConfig{
		DefaultExpiration: time.Duration(5) * time.Minute,
		CleanupInterval:   time.Duration(2) * time.Minute,
		FlushTimerTime:    time.Duration(30) * time.Second,
	})

	// Call Singleton for the first time will create cache.
	cache := cache.Singleton()

	// Create a user service as a flush daemon.
	// And register it into cache daemons.
	us := userService{
		done: make(chan interface{}),
		users: []*User{
			{"Jack", "123"},
			{"Jane", "123456"},
			{"Mark", "abd123"},
			{"Michale", "123aba"},
		},
	}
	cache.Register(ctx, &us)

	user, ok := cache.Get("Jack")
	if ok {
		fmt.Println(user.(*User))
	}
}

To run this example, go to examples/cache-flush/ and run:

go run main.go

You can find a few more examples here. Also see our test-cases in cache_test.go for further working examples.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func InitOnce

func InitOnce(conf CacheConfig)

InitOnce inits cache service configuration only once.

Types

type CacheConfig

type CacheConfig struct {
	// local cache flush time.
	FlushTimerTime time.Duration
	// local cache cleanup time.
	CleanupInterval time.Duration
	// local cache expiration time.
	DefaultExpiration time.Duration
}

CacheConfig sets for cache service daemon.

type CacheFlushDaemon

type CacheFlushDaemon interface {
	// Done tells the cache service quit this cache flush daemon.
	Done(ctx context.Context) (done <-chan interface{})
	// LoadKeys loads keys with current value by cache daemon setting.
	LoadKeys(ctx context.Context, value interface{}) (cacheKeys []string)
	// LoadValues loads values by cache daemon setting.
	LoadValues(ctx context.Context) (values []interface{})
}

CacheFlushDaemon represents a flush daemon will be registered, should do implement of all methods.

type CacheService

type CacheService interface {
	// Set a pair of key-value to cache map.
	Set(k string, v interface{})
	// SetEx a pair of key-value to cache map by expiration.
	SetEx(k string, v interface{}, ex time.Duration)
	// Get the value by key from cache map.
	Get(k string) (v interface{}, ok bool)
	// Del a pair key-value by key.
	Del(k string)
	// GetKeys gets all keys for cache map.
	GetKeys() []string
	// GetValues gets all values for cache map.
	GetValues() []interface{}
	// GetByDefault gets the value by key, if it does not exist key then return default value.
	GetByDefault(k string, v interface{}) interface{}
	// Item gets all items from cache map.
	Item() map[string]cache.Item
	// Flush clears the cache map.
	Flush()
	// Register registers a CacheFlushDaemon to cache service,
	// cache service will flush the cache by ticker time.
	Register(ctx context.Context, daemon CacheFlushDaemon)
}

CacheService represents a cache service interface, package for go-cache.

Set a pair of key-value to cache map.

Get the value by key from cache map.

Register registers a CacheFlushDaemon to cache service, cache service will flush the cache by ticker time.

func Singleton

func Singleton() CacheService

Singleton creates a cache service singleton by lazy mode.

Directories

Path Synopsis
examples
cache-flush command
get-started command

Jump to

Keyboard shortcuts

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