Skip to content

zekroTJA/timedmap

Repository files navigation

~ timedmap ~

A map which has expiring key-value pairs.

       

go get -u github.com/zekroTJA/timedmap/v2

Intro

This package allows to set values to a map which will expire and disappear after a specified time.

Here you can read the docs of this package, generated by pkg.go.dev.

Important

The package has been updated to v2 which will introduce breaking changes to v1.

  • The package now requires a minimum Go version of v1.19.
  • TimedMap and corresponding constructor function now take type parameters for key and value types for improved type safety.
  • Sections have been removed in favor of performance and simplicity of the package.
  • Previously deprecated functions have been removed.

If you experience issues with v1, please create an issue with the specific version mentioned. v1 will still receive updates for bugs and incosistencies alongside v2.


Usage Example

package main

import (
	"log"
	"time"

	"github.com/zekroTJA/timedmap/v2"
)

func main() {

	// Creates a new timed map which scans for
	// expired keys every 1 second
	tm := timedmap.New[string, int](1 * time.Second)

	// Add a key "hey" with the value 213, which should
	// expire after 3 seconds and execute the callback, which
	// prints that the key was expired
	tm.Set("hey", 213, 3*time.Second, func(v int) {
		log.Println("key-value pair of 'hey' has expired")
	})

	// Print key "hey" from timed map
	printKeyVal(tm, "hey")

	// Wait for 5 seconds
	// During this time the main thread is blocked, the
	// key-value pair of "hey" will be expired
	time.Sleep(5 * time.Second)

	// Printing value of key "hey" wil lfail because the
	// key-value pair does not exist anymore
	printKeyVal(tm, "hey")
}

func printKeyVal(tm *timedmap.TimedMap[string, int], key string) {
	d, ok := tm.GetValue(key)
	if !ok {
		log.Println("data expired")
		return
	}

	log.Printf("%v = %d\n", key, d)
}

Further examples, you can find in the examples directory.

If you want to see this package in a practcal use case scenario, please take a look at the rate limiter implementation of the REST API of myrunes.com, where I have used timedmap for storing client-based limiter instances:
https://github.com/myrunes/backend/blob/master/internal/ratelimit/ratelimit.go


Copyright (c) 2020 zekro Development (Ringo Hoffmann).
Covered by MIT licence.