Home > Article > Backend Development > How to use context in Go to implement automatic refresh of request result cache
How to use context in Go to implement automatic refresh of request result cache
Abstract:
In web application development, in order to improve user experience, sometimes we need to cache the results of some requests to reduce Access to databases or other services. However, the validity period of cached data is a problem. Expired cache may cause users to obtain expired data, resulting in erroneous display and operations. In this article, we will explore how to use Go's context package to implement the automatic refresh function of request result cache to ensure the timeliness of cached data.
type CacheItem struct { result interface{} expireAt time.Time } type Cache struct { cacheMap map[string]CacheItem mutex sync.RWMutex }
In the above code, we use a map to store cache items, where the key is the unique identifier related to the request and the value is the cache item details (such as results and expiration time). To ensure concurrency safety, we use a mutex lock.
Next, we need to write a function to obtain cache data. This function first checks whether the request result exists in the cache and determines whether it has expired. If the cached result exists and has not expired, the cached data is returned directly. Otherwise, we need to make the actual request and cache the result. The code is as follows:
func (c *Cache) Get(key string) interface{} { c.mutex.RLock() defer c.mutex.RUnlock() item, ok := c.cacheMap[key] if ok && item.expireAt.After(time.Now()) { return item.result } // 发起请求并更新缓存 result := makeRequest(key) c.cacheMap[key] = CacheItem{result: result, expireAt: time.Now().Add(time.Minute)} return result }
In the above code, we use read locks to read cache items to ensure concurrency safety. If the cache item exists and has not expired, the cache result is returned directly; otherwise, we initiate an actual request and store the request result in the cache.
func (c *Cache) RefreshCache(ctx context.Context, key string) { ticker := time.NewTicker(time.Minute) defer ticker.Stop() for { select { case <-ticker.C: result := makeRequest(key) c.mutex.Lock() c.cacheMap[key] = CacheItem{result: result, expireAt: time.Now().Add(time.Minute)} c.mutex.Unlock() case <-ctx.Done(): return } } }
In the above code, we use a Ticker object to regularly call the makeRequest function to update the cache. At the same time, we use the select statement to listen to the context cancellation signal to exit the refresh loop after the context is canceled. .
package main import ( "context" "fmt" "net/http" "sync" "time" ) type CacheItem struct { result interface{} expireAt time.Time } type Cache struct { cacheMap map[string]CacheItem mutex sync.RWMutex } func makeRequest(key string) interface{} { // 模拟请求耗时 time.Sleep(time.Second) return fmt.Sprintf("result for %s", key) } func (c *Cache) Get(key string) interface{} { c.mutex.RLock() defer c.mutex.RUnlock() item, ok := c.cacheMap[key] if ok && item.expireAt.After(time.Now()) { return item.result } result := makeRequest(key) c.cacheMap[key] = CacheItem{result: result, expireAt: time.Now().Add(time.Minute)} return result } func (c *Cache) RefreshCache(ctx context.Context, key string) { ticker := time.NewTicker(time.Minute) defer ticker.Stop() for { select { case <-ticker.C: result := makeRequest(key) c.mutex.Lock() c.cacheMap[key] = CacheItem{result: result, expireAt: time.Now().Add(time.Minute)} c.mutex.Unlock() case <-ctx.Done(): return } } } func main() { cache := &Cache{cacheMap: make(map[string]CacheItem)} http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Second*5)) defer cancel() key := r.URL.Path result := cache.Get(key) fmt.Fprintf(w, "%s: %s", key, result) // 启动刷新缓存的协程 go cache.RefreshCache(ctx, key) }) http.ListenAndServe(":8080", nil) }
In the above example code, we define a simple HTTP server. When a request is received, the cached Get method is called to obtain the data and returned to the client. At the same time, we use the context package to create a context with a 5-second deadline and pass it to the RefreshCache method to control the refresh time of the cache.
Conclusion:
This article introduces how to use Go's context package to implement the automatic refresh function of the request result cache. By using cache structures and mutexes to ensure concurrency safety, and using the features of the context package to regularly refresh the cache, we can simply cache the request results and ensure the timeliness of the data. The above example code is only a simple demonstration. Actual use may require appropriate modification and optimization based on specific needs.
The above is the detailed content of How to use context in Go to implement automatic refresh of request result cache. For more information, please follow other related articles on the PHP Chinese website!