During the development of a website or application, a page may have different data and resources that need to be loaded, and some of them will be requested frequently. In this case, querying the database or re-fetching resources with every request may cause the website or application to respond slowly. To solve this problem, we can use caching technology. This article will introduce how to implement caching in Golang.
Caching in Golang
There is a package in Golang called "sync", which contains a map concurrency safety implementation of type "Map". We can use this map to implement caching functionality.
The following are the basic steps to implement caching in Golang:
We can define a global Map variable to store cached data . In this Map, we can use strings as "keys" and any type of variables as "values".
var cache = struct { sync.RWMutex items map[string]interface{} }{ items: make(map[string]interface{}), }
In the above code, the sync.RWMutex structure is used to ensure that the cache operation is thread-safe. At the same time, the make function is used to create an empty Map.
func Set(key string, value interface{}, exp time.Duration) { cache.Lock() defer cache.Unlock() cache.items[key] = value if exp > 0 { time.AfterFunc(exp, func() { expire(key) }) } }
In the above code, we use the "Lock" method to ensure that the cache is safe for multiple goroutines accessing it at the same time . After that, we added a key-value pair to the cache, where "key" is the cached key and "value" is the cached value. Finally, we use the "time.AfterFunc" function to set the cache time. When the cache expires, the "expire" method is automatically called to delete the cache.
func Get(key string) (interface{}, bool) { cache.RLock() defer cache.RUnlock() val, ok := cache.items[key] return val, ok }
In the above code, we use the "RLock" method to lock the cache to ensure that multiple goroutines access it simultaneously Cached data can be read freely. Afterwards, we retrieve the corresponding key-value pair from the cache. "val" is the retrieved value and "ok" indicates whether the cache was successfully retrieved.
func Delete(key string) { cache.Lock() defer cache.Unlock() delete(cache.items, key) }
In the above code, we use the "Lock" method to ensure that the cache is safe for multiple goroutines accessing it simultaneously . Then, delete the corresponding key-value pair in the cache.
Sample code
According to the above steps, we can write a simple cache implementation, the code is as follows:
package main import ( "fmt" "sync" "time" ) var cache = struct { sync.RWMutex items map[string]interface{} }{ items: make(map[string]interface{}), } func Set(key string, value interface{}, exp time.Duration) { cache.Lock() defer cache.Unlock() cache.items[key] = value if exp > 0 { time.AfterFunc(exp, func() { expire(key) }) } } func Get(key string) (interface{}, bool) { cache.RLock() defer cache.RUnlock() val, ok := cache.items[key] return val, ok } func Delete(key string) { cache.Lock() defer cache.Unlock() delete(cache.items, key) } func expire(key string) { cache.Lock() defer cache.Unlock() delete(cache.items, key) } func main() { Set("key", "value", time.Second*10) val, ok := Get("key") if ok { fmt.Println(val) } else { fmt.Println("Value not found") } Delete("key") }
In the above example, we use the Set method to cache Add a key-value pair and set the cache time. Then, use the Get method to read the stored value from the cache. Finally, use the Delete method to delete the stored key-value pairs.
Conclusion
In this article, we introduced the method of using the Sync package to implement caching in Golang. This method can be used to improve the efficiency of operating data and reduce unnecessary database queries. Hope this article can help you better understand how caching is implemented in Golang.
The above is the detailed content of Cache implementation golang. For more information, please follow other related articles on the PHP Chinese website!