package cache import ( "fmt" "math/rand" "testing" "time" cherryTime "github.com/cherry-game/cherry/extend/time" "github.com/goburrow/cache" ) func TestMaximumSize(t *testing.T) { fmt.Println("TestMaximumSize") testCache := cache.New( cache.WithMaximumSize(3), cache.WithExpireAfterAccess(3*time.Second), ) for i := 1; i <= 4; i++ { testCache.Put(i, i) } time.Sleep(3 * time.Second) v, found := testCache.GetIfPresent(1) t.Log(v, found) } func TestKeyInt64(t *testing.T) { var key, value int64 key = 247749712289988672 value = 247749712289988672 fmt.Println(key, value) testCache := cache.New( cache.WithMaximumSize(5), cache.WithExpireAfterAccess(5*time.Second), //访问后的5秒钟过期 ) testCache.Put(key, value) v, found := testCache.GetIfPresent(key) fmt.Println(v, found) } func Test111(t *testing.T) { testCache := cache.New( cache.WithMaximumSize(5), cache.WithExpireAfterAccess(5*time.Second), ) for i := 1; i <= 5; i++ { testCache.Put(i, i) } for i := 1; i <= 35; i++ { val, found := testCache.GetIfPresent(1) fmt.Printf("key = %d, val = %+v, found = %v\n", i, val, found) time.Sleep(1 * time.Second) } } func TestCache(t *testing.T) { load := func(k cache.Key) (cache.Value, error) { time.Sleep(100 * time.Millisecond) // Slow task return fmt.Sprintf("%d", k), nil } // CreateGroup a loading cache c := cache.NewLoadingCache(load, cache.WithMaximumSize(100), // Limit number of entries in the cache. cache.WithExpireAfterAccess(3*time.Second), // Expire entries after 1 minute since last accessed. cache.WithRefreshAfterWrite(3*time.Second), // Expire entries after 2 minutes since last created. ) getTicker := time.Tick(4 * time.Second) reportTicker := time.Tick(5 * time.Second) for { select { case <-getTicker: _, _ = c.Get(rand.Intn(200)) case <-reportTicker: st := cache.Stats{} c.Stats(&st) fmt.Printf("%+v\n", st) } } } func TestRefreshAfterWrite(t *testing.T) { testCache := cache.NewLoadingCache( refreshAfterWrite, cache.WithMaximumSize(32), cache.WithExpireAfterWrite(4*time.Second), //cache.WithRefreshAfterWrite(4*time.Second), ) for { val, _ := testCache.Get("a") fmt.Println(val) time.Sleep(2 * time.Second) } } func refreshAfterWrite(key cache.Key) (cache.Value, error) { fmt.Println("refresh " + cherryTime.Now().String()) return rand.Intn(500), nil }