LoginSignup
2
1

シンプルなインメモリキャッシュ go-cache

Posted at

go-cache

キャッシュというと、Redisやmemcachedなどが有名所ですが、Goではインメモリなキャッシュを扱うことができます。アイテムごとにTTLを設定でき、取り扱いがシンプルなgo-cacheを紹介します。

インストール

go get github.com/patrickmn/go-cache
main.go
package main

import (
	"fmt"
	"time"

	"github.com/patrickmn/go-cache"
)

func main() {
    // TTL設定
    c := cache.New(30*time.Second, 2*time.Minute)
    c.Set("key", "value", cache.DefaultExpiration)

    val, found := c.Get("key")
    if found {
        fmt.Println("Found key:", val)
    } else {
        fmt.Println("key not found")
    }
    // 揮発しているか確認
	time.Sleep(1 * time.Minute)
	fmt.Println("1分経過")
	_, found = c.Get("key")
	if found {
		fmt.Println("Found key:", val)
	} else {
		fmt.Println("key not found")
	}
}

実行してみます。

go run main.go
Found key: value
1分経過
key not found
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1