【ChatGPT】Go语言实现一个内存缓存服务

86 阅读1分钟

下面是一个简单的内存缓存服务的Go语言实现:

package main

import (
    "fmt"
    "sync"
    "time"
)

type cacheItem struct {
    value      interface{}
    expireTime time.Time
}

type cache struct {
    items map[string]cacheItem
    lock  sync.RWMutex
}

func newCache() *cache {
    return &cache{
        items: make(map[string]cacheItem),
    }
}

func (c *cache) get(key string) (interface{}, bool) {
    c.lock.RLock()
    defer c.lock.RUnlock()

    item, found := c.items[key]

    if !found {
        return nil, false
    }

    if item.expireTime.Before(time.Now()) {
        delete(c.items, key)
        return nil, false
    }

    return item.value, true
}

func (c *cache) set(key string, value interface{}, ttl time.Duration) {
    c.lock.Lock()
    defer c.lock.Unlock()

    expireTime := time.Now().Add(ttl)
    c.items[key] = cacheItem{value, expireTime}
}

func main() {
    c := newCache()

    c.set("key1", 123, time.Second*10)
    c.set("key2", "value2", time.Second*20)

    v1, found1 := c.get("key1")
    v2, found2 := c.get("key2")
    v3, found3 := c.get("key3")

    fmt.Println(v1, found1)
    fmt.Println(v2, found2)
    fmt.Println(v3, found3)

    time.Sleep(time.Second * 15)

    v4, found4 := c.get("key1")
    fmt.Println(v4, found4)
}

在上面的示例代码中,cache 结构体中的 items 字段是用来存放缓存数据的,lock 则用来进行锁控制,以保证并发安全。

set 方法用来设置缓存数据,其中参数 ttl 表示缓存数据的有效期。

get 方法用来获取缓存数据,会先检查缓存数据是否已经过期,如果过期则会删除缓存数据。

main 函数中,我们使用 newCache 函数创建了一个新的缓存对象,并使用 set 方法设置了两个缓存数据。

接着我们使用 get 方法获取了三个缓存数据,其中 key1key2 对应的缓存数据是存在的,key3 对应的缓存数据则不存在。

最后我们使用 time.Sleep 函数暂停了 15 秒,再次使用 get 方法获取了 key1 对应的缓存数据,此时由于 key1 对应的缓存数据已经过期,所以 get 方法返回了不存在的状态。