goでローカルキャッシュを実現する方法

Go言語では、ローカルキャッシュの実現に`sync.Map`または`map`を使用できます。1. `sync.Map`を使用したローカルキャッシュの実現:

package main
import (
"sync"
"time"
)
type Cache struct {
data sync.Map
}
func (c *Cache) Get(key string) (interface{}, bool) {
value, ok := c.data.Load(key)
if ok {
return value, true
}
return nil, false
}
func (c *Cache) Set(key string, value interface{}) {
c.data.Store(key, value)
}
func (c *Cache) Delete(key string) {
c.data.Delete(key)
}
func main() {
cache := &Cache{}
cache.Set("key1", "value1")
cache.Set("key2", "value2")
value, ok := cache.Get("key1")
if ok {
println(value.(string)) // 输出:value1
}
cache.Delete("key2")
value, ok = cache.Get("key2")
if !ok {
println("key2 not found") // 输出:key2 not found
}
}

map によるローカルキャッシュの実装:

package main
import "time"
type Cache struct {
data   map[string]interface{}
expiry map[string]time.Time
}
func (c *Cache) Get(key string) (interface{}, bool) {
value, ok := c.data[key]
if ok {
expiryTime := c.expiry[key]
if expiryTime.After(time.Now()) {
return value, true
} else {
delete(c.data, key)
delete(c.expiry, key)
return nil, false
}
}
return nil, false
}
func (c *Cache) Set(key string, value interface{}, expiry time.Duration) {
c.data[key] = value
c.expiry[key] = time.Now().Add(expiry)
}
func (c *Cache) Delete(key string) {
delete(c.data, key)
delete(c.expiry, key)
}
func main() {
cache := &Cache{
data:   make(map[string]interface{}),
expiry: make(map[string]time.Time),
}
cache.Set("key1", "value1", time.Second*10)
cache.Set("key2", "value2", time.Second*20)
value, ok := cache.Get("key1")
if ok {
println(value.(string)) // 输出:value1
}
time.Sleep(time.Second * 15)
value, ok = cache.Get("key1")
if !ok {
println("key1 not found") // 输出:key1 not found
}
}

Go言語においてネイティブなキャッシュを実装するための一般的な2つの方法を以下に示します。使用方法は、自己の同時実行の安全性とパフォーマンスの必要性によって決まります。

bannerAds