Golang 通过内存缓存来提升性能
    		       		warning:
    		            这篇文章距离上次修改已过423天,其中的内容可能已经有所变动。
    		        
        		                
                
package main
 
import (
    "fmt"
    "time"
)
 
// 缓存结构体
type Cache struct {
    data map[string]interface{}
}
 
// 缓存写入
func (c *Cache) Set(key string, value interface{}, expireTime time.Duration) {
    c.data[key] = value
    go func() {
        time.Sleep(expireTime)
        delete(c.data, key)
    }()
}
 
// 缓存读取
func (c *Cache) Get(key string) (interface{}, bool) {
    if val, ok := c.data[key]; ok {
        return val, true
    }
    return nil, false
}
 
func main() {
    // 创建缓存实例
    cache := &Cache{
        data: make(map[string]interface{}),
    }
 
    // 写入缓存
    cache.Set("exampleKey", "exampleValue", 5*time.Second)
 
    // 读取缓存
    if val, ok := cache.Get("exampleKey"); ok {
        fmt.Printf("从缓存中获取的值: %v\n", val)
    } else {
        fmt.Println("缓存中没有找到对应的值")
    }
 
    // 等待5秒后,缓存的值会被自动删除
    time.Sleep(5*time.Second)
 
    // 再次读取缓存
    if val, ok := cache.Get("exampleKey"); ok {
        fmt.Printf("从缓存中获取的值: %v\n", val)
    } else {
        fmt.Println("缓存中没有找到对应的值")
    }
}这段代码展示了如何在Go语言中通过Cache结构体来实现简单的内存缓存。Set方法用于写入缓存,并设置一个过期时间,过期后自动删除。Get方法用于读取缓存。代码中使用了time.Sleep来模拟时间流逝,并验证了缓存数据确实在指定时间后被删除。
评论已关闭