1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

GoのbigCacheのサンプルコード

Last updated at Posted at 2024-10-06

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)
})

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?