github.com/bytedance/gopkg@v0.0.0-20240514070511-01b2cbcf35e1/cache/asynccache/README.md (about) 1 # asynccache 2 3 ## Introduction 4 5 `asynccache` fetches and updates the latest data periodically and supports expire a key if unused for a period. 6 7 The functions it provides is listed below: 8 ```go 9 type AsyncCache interface { 10 // SetDefault sets the default value of given key if it is new to the cache. 11 // It is useful for cache warming up. 12 // Param val should not be nil. 13 SetDefault(key string, val interface{}) (exist bool) 14 15 // Get tries to fetch a value corresponding to the given key from the cache. 16 // If error occurs during the first time fetching, it will be cached until the 17 // sequential fetching triggered by the refresh goroutine succeed. 18 Get(key string) (val interface{}, err error) 19 20 // GetOrSet tries to fetch a value corresponding to the given key from the cache. 21 // If the key is not yet cached or error occurs, the default value will be set. 22 GetOrSet(key string, defaultVal interface{}) (val interface{}) 23 24 // Dump dumps all cache entries. 25 // This will not cause expire to refresh. 26 Dump() map[string]interface{} 27 28 // DeleteIf deletes cached entries that match the `shouldDelete` predicate. 29 DeleteIf(shouldDelete func(key string) bool) 30 31 // Close closes the async cache. 32 // This should be called when the cache is no longer needed, or may lead to resource leak. 33 Close() 34 } 35 ``` 36 37 ## Example 38 39 ```go 40 var key, ret = "key", "ret" 41 opt := Options{ 42 RefreshDuration: time.Second, 43 IsSame: func(key string, oldData, newData interface{}) bool { 44 return false 45 }, 46 Fetcher: func(key string) (interface{}, error) { 47 return ret, nil 48 }, 49 } 50 c := NewAsyncCache(opt) 51 52 v, err := c.Get(key) 53 assert.NoError(err) 54 assert.Equal(v.(string), ret) 55 56 time.Sleep(time.Second / 2) 57 ret = "change" 58 v, err = c.Get(key) 59 assert.NoError(err) 60 assert.NotEqual(v.(string), ret) 61 62 time.Sleep(time.Second) 63 v, err = c.Get(key) 64 assert.NoError(err) 65 assert.Equal(v.(string), ret) 66 ```