Skip to content

EmirShimshir/inMemoryCache

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

15 Commits
 
 
 
 
 
 
 
 

Repository files navigation

Go thread-safe in-memory cache with element time-to-live.

Installation

go get -u github.com/EmirShimshir/inMemoryCache

Description

Go in-memory cache is goroutine-safe, it helps you store data of different types in a cache and access them by key. When adding a new element to the cache, specify the time after which the element will be unavailable.

inMemoryCache.New() - constructor for new cache

Set(key string, value any, ttl time.Duration) error - write the value to the cache by the key. The key must not be empty. The ttl is time to live for the new element, it must not be zero.

Get(key string) (interface{}, error) - get the value from the cache by the key. The key must not be empty and the value must exist.

Delete(key) error - delete the value from the cache by the key. The key must not be empty and the value must exist.

Example

package main

import (
	"fmt"
	"log"
	"time"

	"github.com/EmirShimshir/inMemoryCache"
)

func main() {
	var cache inMemoryCache.Cache
	cache = inMemoryCache.New()

	err := cache.Set("userId", 42, 5 * time.Second)
	if err != nil { // err == nil
		log.Fatal(err)
	}

	userId, err := cache.Get("userId")
	if err != nil { // err == nil
		log.Fatal(err)
	}
	fmt.Println(userId) // Output: 42

	time.Sleep(6 * time.Second)

	userId, err = cache.Get("userId")
	if err != nil { // err != nil
		log.Fatal(err) // <--
	}
}
42
2022/07/27 14:43:08 no value for the key userId
exit status 1

About

In-memory cache written in Go

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages