Giter Site home page Giter Site logo

memory-cache's Introduction

Simple thread save memory cache

Features:

  • generic
  • thread save
  • TTL
  • optional fixed size (after defined capacity is reached, oldest element is distracted)
  • async GC of expired keys

How to use

package main

import (
	"fmt"
	mcache "github.com/mkelcik/memory-cache"
	"time"
)

type CacheValue struct {
	Value int
}

func main() {
	// define type of key and value
	// first parameter is pre allocation size
	// if second parameter is true, cache is limited to this size, if false the cache can grow beyond this capacity
	// third parameter is ttl duration for records, if is set to 0 the cache items never expire
	// last parameter is GC interval in seconds, if set to 0, GC will never start automatically
	cache := mcache.NewCache[int, CacheValue](100, false, 60 * time.Second, 120 * time.Second)

	// set data to cache
	for i := 1; i <= 100; i++ {
		cache.Set(i, CacheValue{Value: 1})
	}

	// read from cache 
	itemFromCache, ok := cache.Get(1)
	if ok {
		fmt.Println("value is:", itemFromCache.Value)
	}
}

Execute GC manually

If you need more control over destroying expired key, you can run GC manually when you see fit

cache.GCRun()

memory-cache's People

Contributors

mkelcik avatar

Stargazers

 avatar  avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.