GoのbigCacheのサンプルコード
更新日:2025/3/13/(木) 12:38
タグ:Go
bigCacheのリポジトリ
https://github.com/allegro/bigcache
Example(echo使用)
// キャッシュの設定 config := bigcache.Config{ // シャードの数(2のべき乗でなければならない) Shards: 1024, // エントリが削除されるタイムアウトの時間 LifeWindow: 10 * time.Minute, // 期限切れのエントリを削除する間隔 CleanWindow: 30 * time.Second, } // キャッシュの初期化(アプリケーション実行時のみ行うmain.goやroute.goなど) cache, err := bigcache.NewBigCache(config) if err != nil { e.Logger.Fatal(err) } // キャッシュお試しのルート cacheGroup := publicGroup.Group("/cache") cacheGroup.GET("/set", func(c echo.Context) error { err = cache.Set("hoge", []byte("hogehoge")) err = cache.Set("foo", []byte("foofoo")) err = cache.Set("buzz", []byte("buzzbuzz")) err = cache.Set("fuga", []byte("fugafuga")) return c.JSON(http.StatusOK, "set done") }) cacheGroup.GET("/list", func(c echo.Context) error { iterator := cache.Iterator() results := make(map[string]string) for iterator.SetNext() { entry, err := iterator.Value() if err != nil { return c.JSON(http.StatusInternalServerError, "キャッシュのエントリを取得できませんでした") } results[entry.Key()] = string(entry.Value()) } return c.JSON(http.StatusOK, results) })