World Conquest Chronicles

World Conquest Chronicles

go-cache, v1.0

The library that implements an in-memory cache with garbage collection in two modes: total (based on a full scan) and partial (based on expiration in Redis).

Major version.

Features

  • implementation of an in-memory cache:
    • operations:
      • getting a value by a key:
        • signaling a reason for the absence of a key - missed or expired;
      • getting a value by a key with deletion of expired values:
        • signaling a reason for the absence of a key - missed or expired;
      • setting a key-value pair with a specified time to live:
        • support of key-value pairs without a set time to live (persistent);
      • deletion.

Examples

cache.NewCache():

package main

import (
    "fmt"
    "hash/fnv"
    "io"
    "time"

    hashmap "github.com/thewizardplusplus/go-hashmap"
)

type StringKey string

func (key StringKey) Hash() int {
    hash := fnv.New32()
    io.WriteString(hash, string(key))

    return int(hash.Sum32())
}

func (key StringKey) Equals(other interface{}) bool {
    return key == other.(StringKey)
}

func main() {
    storage := hashmap.NewConcurrentHashMap()
    timeZones := NewCache(storage, time.Now)
    timeZones.Set(StringKey("EST"), -5*60*60, 100*time.Millisecond)
    timeZones.Set(StringKey("CST"), -6*60*60, 100*time.Millisecond)
    timeZones.Set(StringKey("MST"), -7*60*60, 100*time.Millisecond)

    estOffset, err := timeZones.Get(StringKey("EST"))
    fmt.Println(estOffset, err)

    time.Sleep(200 * time.Millisecond)

    estOffset, err = timeZones.Get(StringKey("EST"))
    fmt.Println(estOffset, err)

    // Output:
    // -18000 <nil>
    // <nil> key expired
}

Benchmarks

BenchmarkCacheGetting/Get-8             10000000          1641 ns/op         352 B/op         36 allocs/op
BenchmarkCacheGetting/GetWithGC-8        5000000          3291 ns/op         575 B/op         57 allocs/op

Repository

Link: https://github.com/thewizardplusplus/go-cache/tree/v1.0.

Content: code.

License: MIT.