美文网首页
Beego 中容易被我们忽视的Memory 缓存问题

Beego 中容易被我们忽视的Memory 缓存问题

作者: leechan0x01 | 来源:发表于2020-04-12 01:06 被阅读0次

前言

在我基于 beego 写博客的时候遇到一个很奇怪的问题,那就是在使用 Memory Cache 类型缓存的时候,缓存不生效很是奇怪,但是使用 redis 就没问题。由于时间问题我就没有深究,毕竟那时候实际上也会选用Memory做缓存的。所以就放了下来,直到今天在群里有人问了同样的问题。我决定去研究一下这个坑。

我们先来看一个例子

Set Cache 代码:

var (
    urlcache cache.Cache
)

func init() {
    urlcache, _ = cache.NewCache("memory", `{"interval":10}`)
}


func (this *SetController) Get() {
        urlcache.Put("test", "test result sada", 60)
}

Get Cache 代码:

func (this *GetController) Get() {

    result := urlcache.Get("test")

    this.Data["json"] = result
    this.ServeJSON()
}

先卖个关子,先别往下看,思考一下你们觉得输出的结果是什么?

没错,结果是:

null

那么我们再看一下例子:

Set Cache 代码:

var (
    urlcache cache.Cache
)

func init() {
    urlcache, _ = cache.NewCache("memory", `{"interval":10}`)
}


func (this *SetController) Get() {
        urlcache.Put("test", "test result sada", 0)
}

Get Cache 代码:

func (this *GetController) Get() {

    result := urlcache.Get("test")

    this.Data["json"] = result
    this.ServeJSON()
}

再来猜一下这回结果是什么?

大家可能都知道了,结果:

test result sada

那纠究竟是为什么会这样呢?真相只有一个!

原来这个 Put 的第三个参数,设置内存的 GC 的时间单位是 time.Duration 也就是我们说的纳秒,所以我们在直接设置这个时间的时候经常忽略单位只写了个数字,所以最后我们回头取缓存的时候,缓存早已经过期的了。
这个事情告诉我们看文档一定要细心。我贴一下文档以及 Cache 源码:

官方文档给的接口:

type Cache interface {
    Get(key string) interface{}
    GetMulti(keys []string) []interface{}
    Put(key string, val interface{}, timeout time.Duration) error
    Delete(key string) error
    Incr(key string) error
    Decr(key string) error
    IsExist(key string) bool
    ClearAll() error
    StartAndGC(config string) error
}

memory.go源码:

// Put cache to memory.
// if lifespan is 0, it will be forever till restart.
func (bc *MemoryCache) Put(name string, value interface{}, lifespan time.Duration) error {
    bc.Lock()
    defer bc.Unlock()
    bc.items[name] = &MemoryItem{
        val:         value,
        createdTime: time.Now(),
        lifespan:    lifespan,
    }
    return nil
}

欢迎各位朋友留言评论一起学习交流。

原文链接:http://leechan.online/detail/10.html

相关文章

  • Beego 中容易被我们忽视的Memory 缓存问题

    前言 在我基于 beego 写博客的时候遇到一个很奇怪的问题,那就是在使用 Memory Cache 类型缓存的时...

  • 无标题文章

    浏览器缓存 200 from memory cache 不访问服务器,直接读缓存,从内存中读取缓存。此时的数据时缓...

  • 2019-08-05

    餐厅装修是一个很容易被大家忽视的问题 我突然发现,餐厅装修是一个很容易被大家忽视的问题。 很多人在网上找客厅怎么布...

  • PHP操作Memcache

    Memcache简介 cache in memory 缓存数据存储到内存中nosql not only sql...

  • 浏览器缓存

    http状态码 200 from memory cache 不访问服务器,直接读缓存,从内存中读取缓存。此时的数据...

  • redis缓存雪崩、缓存击穿、缓存穿透

    缓存雪崩、缓存击穿、缓存穿透 ———Sidfate 今天我们讲讲用redis缓存时容易遇到的一些问题。首先要明确一...

  • HTTP缓存机制

    两种缓存位置 使用哪种缓存位置由浏览器内部机制决定 from memory cache从内存中获取,倾向于缓存更新...

  • 浏览器缓存类型

    强缓存 强缓存指的是缓存在内存(Memory Cache)和硬盘(Disk Cache)的内容。 强缓存的产生依赖...

  • 深入浏览器缓存机制

    深入浏览器缓存机制 我们在开发过程中可能经常看到 200 (memory cache) 200 (disk cac...

  • 深拷贝与浅拷贝

    CPU缓存 (Cache Memory) CPU缓存中存放了CPU短时间内需要访问的数据,从而加快运算速度.CPU...

网友评论

      本文标题:Beego 中容易被我们忽视的Memory 缓存问题

      本文链接:https://www.haomeiwen.com/subject/dpummhtx.html