Lock in $30 Savings on PRO—Offer Ends Soon! ⏳

ttlcacheのここがスゴい

 ttlcacheのここがスゴい

Fukuoka.go#20 でお話しました。

Kazuhiko Yamashita

October 23, 2024
Tweet

More Decks by Kazuhiko Yamashita

Other Decks in Programming

Transcript

  1. 🍉🌴🏄 GoConference’19 🏄🌴🍉 ࢁԼ ࿨඙ @pyama86 <?php $pro fi le

    = [ 'ॴଐ' => 'GMOϖύϘ ٕज़ج൫νʔϜ', ‘ݞॻ' => 'γχΞɾϓϦϯγύϧ', 'झຯ' => ['ώϧτϯ८Γ', 'Ωϟϯϓ', ‘ཱྀߦ’,’εϚϒϥ’], '΢ΣϒαΠτ' => [ 'life' => 'http://pyama.fun', 'stns' => 'http://stns.jp', ], ]; 2
  2. 🍉🌴🏄 GoConference’19 🏄🌴🍉 ttlcache w ػೳ͕গͳ͍γϯϓϧͳ 55-෇͖ͷΦϯϝϞϦΩϟογϡ w σϑΥϧτ͸55-͕ࣗಈԆ௕͞ΕΔ w

    Ϩίʔυͷ௥Ճ࣌ɺ࡟আ࣌ʹ ϑοΫ͕࣮ߦͰ͖Δ w -PBEFS΋͋ΓଟॏΫΤϦΛ཈੍Ͱ͖Δ 4 package main import ( "time" "github.com/jellydator/ttlcache" ) func main() { cache := ttlcache.New[string, string]( ttlcache.WithTTL[string, string](time.Minute), ) go cache.Start() }
  3. 🍉🌴🏄 GoConference’19 🏄🌴🍉 Hooks 5 cache.OnInsertion(func(ctx context.Context, item *ttlcache.Item[string, string])

    { tracer.Increment(item.Value(), item.ExpiresAt()) }) cache.OnEviction(func(ctx context.Context, reason ttlcache.EvictionReason, item *ttlcache.Item[string, string]) { if reason == ttlcache.EvictionReasonCapacityReached { slack.Notify(item.Value(), item.ExpiresAt()) } }) ௨஌ͨ͠ΓɺΧ΢ϯλʔΛೖΕͨΓ
  4. 🍉🌴🏄 GoConference’19 🏄🌴🍉 Loader 7 loader := ttlcache.LoaderFunc[…](func(…, key string))

    *ttlcache.Item[string, int] { return runQuery(fmt.Sprintf(`SELECT * FROM name = “%s”`, key) }) group := &singleflight.Group{} sl := ttlcache.NewSuppressedLoader[string, string](loader, group) cache := ttlcache.New[string, int]( ttlcache.WithTTL[string, int](30*time.Minute), ttlcache.WithLoader[string, int](sl), ) cache.Get(“gopher”) Ωϟογϡ͕ͳ͍ͱ͖ʹɺϩʔυ͢ΔίʔϧόοΫ
  5. 🍉🌴🏄 GoConference’19 🏄🌴🍉 single fl ight.Group 8 var g singleflight.Group

    for i := 0; i < 3; i++ { go func(i int) { v, _, _ := g.Do("cache_key", func() (interface{}, error) { fmt.Println("Fetching from origin...") time.Sleep(2 * time.Second) return "response_data", nil }) fmt.Printf("Result for goroutine %d: %v\n", i, v) }(i) } ଟॏ࣮ߦΛҰͭͷ࣮ߦʹ·ͱΊΔ͜ͱ͕Ͱ͖Δ
  6. 🍉🌴🏄 GoConference’19 🏄🌴🍉 single fl ight.Group 9 Fetching from origin...

    Result for goroutine 0: response_data Result for goroutine 1: response_data Result for goroutine 2: response_data ϑΣον͸ճɺ݁Ռ͸ߦ 'FUDI͸ճ͚࣮ͩߦ