cache

package module
v0.0.0-...-4204c4f Latest Latest
Warning

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

Go to latest
Published: May 20, 2020 License: MIT Imports: 6 Imported by: 0

README

Build Status

Cache using MongoDB for Go

Install

go get github.com/mehmetalisavas/mongo-cache

Description about package

In this package, while creating constructor, self-referential function is used to avoid passing nil value to the function as parameter. It might be confusing at first, but all required functions are granted for usage. After creating constructor, you can set necessary field with config options (you can see at examples or take a look tests)

Usage

var session = initMongo() // you need to create a session for mongoDB

// Init MongoCache with defaults
NewMongoCacheWithTTL(session)

// Init MongoCache with TTL option
duration := time.Minute * 3
cacheTTL := NewMongoCacheWithTTL(session, SetTTL(duration))

// Also you can pass multiple config options while initing MongoCache
NewMongoCacheWithTTL(session, SetTTL(duration/2), SetGCInterval(duration), StartGC())

Granted Config options are listed below:
- func MustEnsureIndexExpireAt() Option
- func StartGC() Option // starts the garbage collector
- func SetTTL(duration time.Duration) Option // sets the ttl for cache
- func SetGCInterval(duration time.Duration) Option 
- func SetCollectionName(collName string) Option // sets the specific collection name for mongo session

Examples


// session is the default session with default options
// initMongo function is just used for testing.
// (you should initialize your own mongo db)
var session = initMongo()


mgoCache := NewMongoCacheWithTTL(session)
defer mgoCache.StopGC()

key := "cacheType"
value := "mongoDB"

if err := mgoCache.Set(key, value); err != nil {
    return err
}
data, err := mgoCache.Get(key) // "key" : "value"
if err != nil {
    return err
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNotFound = errors.New("not found")
)

Functions

This section is empty.

Types

type Document

type Document struct {
	Key      string      `bson:"_id" json:"_id"`
	Value    interface{} `bson:"value" json:"value"`
	ExpireAt time.Time   `bson:"expireAt" json:"expireAt"`
}

Document holds the key-value pair for mongo cache

type MongoCache

type MongoCache struct {

	// CollectionName speficies the optional collection name for mongoDB
	// if CollectionName is not set, then default value will be set
	CollectionName string

	// ttl is a duration for a cache key to expire
	TTL time.Duration

	// GCInterval specifies the time duration for garbage collector time interval
	GCInterval time.Duration

	// GCStart starts the garbage collector and deletes the
	// expired keys from mongo with given time interval
	GCStart bool

	// Mutex is used for handling the concurrent
	// read/write requests for cache
	sync.RWMutex
	// contains filtered or unexported fields
}

MongoCache holds the cache values that will be stored in mongoDB

func NewMongoCacheWithTTL

func NewMongoCacheWithTTL(session *mgo.Session, configs ...Option) *MongoCache

NewMongoCacheWithTTL creates a caching layer backed by mongo. TTL's are managed either by a background cleaner or document is removed on the Get operation. Mongo TTL indexes are not utilized since there can be multiple systems using the same collection with different TTL values.

The responsibility of stopping the GC process belongs to the user.

Session is not closed while stopping the GC.

This self-referential function satisfy you to avoid passing nil value to the function as parameter e.g (usage) : configure with defaults, just call; NewMongoCacheWithTTL(session)

configure ttl duration with;

NewMongoCacheWithTTL(session, func(m *MongoCache) {
		m.TTL = 2 * time.Minute
})

or NewMongoCacheWithTTL(session, SetTTL(time.Minute * 2))

configure collection name with;

NewMongoCacheWithTTL(session, func(m *MongoCache) {
		m.CollectionName = "MongoCacheCollectionName"
})

func (*MongoCache) Delete

func (m *MongoCache) Delete(key string) error

Delete deletes a given key if exists

func (*MongoCache) EnsureIndex

func (m *MongoCache) EnsureIndex() error

EnsureIndex ensures the index with expireAt key

func (*MongoCache) Get

func (m *MongoCache) Get(key string) (interface{}, error)

Get returns a value of a given key if it exists

func (*MongoCache) Set

func (m *MongoCache) Set(key string, value interface{}) error

Set will persist a value to the cache or override existing one with the new one

func (*MongoCache) SetEx

func (m *MongoCache) SetEx(key string, duration time.Duration, value interface{}) error

SetEx will persist a value to the cache or override existing one with the new one with ttl duration

func (*MongoCache) StartGC

func (m *MongoCache) StartGC(gcInterval time.Duration)

StartGC starts the garbage collector with given time interval The expired data will be checked & deleted with given interval time

func (*MongoCache) StopGC

func (m *MongoCache) StopGC()

StopGC stops sweeping goroutine.

type Option

type Option func(*MongoCache)

Option sets the options specified.

func MustEnsureIndexExpireAt

func MustEnsureIndexExpireAt() Option

MustEnsureIndexExpireAt ensures the expireAt index usage: NewMongoCacheWithTTL(mongoSession, MustEnsureIndexExpireAt())

func SetCollectionName

func SetCollectionName(collName string) Option

SetCollectionName sets the collection name for mongoDB in MongoCache struct as option usage: NewMongoCacheWithTTL(mongoSession, SetCollectionName("mongoCollName"))

func SetGCInterval

func SetGCInterval(duration time.Duration) Option

SetGCInterval sets the garbage collector interval in MongoCache struct as option usage: NewMongoCacheWithTTL(mongoSession, SetGCInterval(time*Minute))

func SetTTL

func SetTTL(duration time.Duration) Option

SetTTL sets the ttl duration in MongoCache as option usage: NewMongoCacheWithTTL(mongoSession, SetTTL(time*Minute))

func StartGC

func StartGC() Option

StartGC enables the garbage collector in MongoCache struct usage: NewMongoCacheWithTTL(mongoSession, StartGC())

Jump to

Keyboard shortcuts

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