mapcache

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2024 License: Apache-2.0 Imports: 6 Imported by: 3

README

mapcache

Godoc Reference Go Coverage Go Report Card

A type-safe, concurrent in-memory key-value cache for Go with TTL support.

Features

  • 🔒 Thread-safe operations
  • 📦 Generic type support
  • ⏰ TTL (Time To Live) support
  • 🧹 Automatic cleanup of expired entries
  • 🔄 Iterator support for cache entries
  • 💪 Zero external dependencies

Installation

go get github.com/omniaura/mapcache

Usage

Basic Usage
package main

import (
    "fmt"
    "github.com/omniaura/mapcache"
)

func main() {
    // Create a new string->int cache
    cache, _ := mapcache.New[string, int]()

    // Get or compute a value
    value, err := cache.Get("mykey", func() (int, error) {
        // This function is only called if the value isn't cached
        // or has expired
        return 42, nil
    })
    
    if err != nil {
        panic(err)
    }
    fmt.Println(value) // Output: 42
    
    // Subsequent calls will return the cached value
    value, _ = cache.Get("mykey", func() (int, error) {
        // This won't be called since the value is cached
        return 100, nil
    })
    fmt.Println(value) // Still outputs: 42
}
With TTL (Time To Live)
package main

import (
    "time"
    "github.com/omniaura/mapcache"
)

func main() {
    // Create cache with 5 minute TTL
    cache, _ := mapcache.New[string, int](
        mapcache.WithTTL(5 * time.Minute),
    )

    // Values will expire after 5 minutes
    cache.Get("key", func() (int, error) {
        return 42, nil
    })
    
    // You can also override TTL per-request
    cache.Get("key", func() (int, error) {
        return 42, nil
    }, mapcache.WithTTL(10 * time.Second))
}
With Automatic Cleanup
package main

import (
    "context"
    "time"
    "github.com/omniaura/mapcache"
)

func main() {
    ctx := context.Background()
    
    // Create cache with TTL and cleanup every minute
    cache, _ := mapcache.New[string, int](
        mapcache.WithTTL(5 * time.Minute),
        mapcache.WithCleanup(ctx, time.Minute),
    )

    // Expired entries will be automatically removed every minute
}
Pre-allocated Size
package main

import "github.com/omniaura/mapcache"

func main() {
    // Create cache with pre-allocated size
    cache, _ := mapcache.New[string, int](
        mapcache.WithSize(100),
    )
}
Iterating Over Cache Entries
package main

import (
    "fmt"
    "github.com/omniaura/mapcache"
)

func main() {
    cache, _ := mapcache.New[string, int]()
    
    // Add some values
    cache.Get("one", func() (int, error) { return 1, nil })
    cache.Get("two", func() (int, error) { return 2, nil })
    
    // Sequential iteration
    for k, v := range cache.All() {
        fmt.Printf("Key: %s, Value: %d\n", k, v.V)
    }
    
    // Parallel iteration (for concurrent processing)
    for k, v := range cache.AllParallel() {
        go func(key string, value int) {
            fmt.Printf("Processing: %s=%d\n", key, value)
        }(k, v.V)
    }
}
Error Handling
package main

import (
    "errors"
    "github.com/omniaura/mapcache"
)

func main() {
    cache, _ := mapcache.New[string, int]()
    
    // Handle errors from the update function
    value, err := cache.Get("key", func() (int, error) {
        return 0, errors.New("failed to compute value")
    })
    
    if err != nil {
        // Handle error
    }
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Item

type Item[V any] struct {
	V         V
	UpdatedAt time.Time
}

type MapCache

type MapCache[K comparable, V any] struct {
	TTL time.Duration
	// contains filtered or unexported fields
}

func New

func New[K comparable, V any](opts ...OptFunc) (*MapCache[K, V], error)

func (*MapCache[K, V]) All

func (mc *MapCache[K, V]) All() iter.Seq2[K, Item[V]]

func (*MapCache[K, V]) AllParallel

func (mc *MapCache[K, V]) AllParallel() iter.Seq2[K, Item[V]]

func (*MapCache[K, V]) Get

func (mc *MapCache[K, V]) Get(key K, up func() (V, error), opts ...OptFunc) (V, error)

type OptFunc

type OptFunc func(*options) error

func WithCleanup

func WithCleanup(ctx context.Context, interval time.Duration) OptFunc

func WithSize

func WithSize(size int) OptFunc

func WithTTL

func WithTTL(ttl time.Duration) OptFunc

Jump to

Keyboard shortcuts

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