Revel 緩存Cache

2022-07-28 14:10 更新

Revel 提供了一個服務(wù)器端、臨時的、低延遲存儲的緩存庫。對于頻繁訪問數(shù)據(jù)庫中緩慢變化的數(shù)據(jù),使用緩存一個很好的方法,并且它也可以用于實(shí)現(xiàn)用戶session (如果基于cookie的session不足).

參考 緩存接口

過期時間

緩存有三種過期時間:

  • ?time.Duration?,指定一個過期時間。
  • cache.DEFAULT, 默認(rèn)過期時間(1小時)。
  • cache.FOREVER, 永不過期。

重要提示:調(diào)用者不能依賴于存在于緩存中內(nèi)容,因為數(shù)據(jù)是不持久保存,重新啟動后,會清除所有緩存數(shù)據(jù)。

序列化

緩存讀寫接口自動為調(diào)用者序列化任何類型的的值。有以下幾種方式:

  • 如果是 []byte類型, 數(shù)據(jù)保持不變。
  • 如果是 整數(shù)類型, 數(shù)據(jù)被保存為 ASCII。
  • 其他類型,使用 encoding/gob進(jìn)行編碼。

實(shí)現(xiàn)

緩存通過以下幾種方式進(jìn)行配置:

  • 分布式memcached 主機(jī)緩存
  • 單獨(dú) redis 主機(jī)緩存
  • 本地內(nèi)存緩存

配置

app.conf中配置緩存:

  • cache.expires - 一個字符串,time.ParseDuration 類型,指定一個過期時間 (默認(rèn)1小時)
  • cache.memcached -一個布爾值,是否開啟memcached緩存 (默認(rèn)不開啟)
  • cache.redis -一個布爾值,是否開啟redis緩存 (默認(rèn)不開啟)
  • cache.hosts - 緩存的主機(jī)列表(多個主機(jī)使用逗號分隔),cache.memcached開啟后有效。

例如

下面是常見操作的一個例子。請注意,如果不需要調(diào)用的結(jié)果來處理請求,調(diào)用者可以在新的goroutine調(diào)用緩存操作。

import (
    "github.com/revel/revel"
    "github.com/revel/revel/cache"
)

func (c App) ShowProduct(id string) revel.Result {
    var product Product
    if err := cache.Get("product_"+id, &product); err != nil {
        product = loadProduct(id)
        go cache.Set("product_"+id, product, 30*time.Minute)
    }
    return c.Render(product)
}

func (c App) AddProduct(name string, price int) revel.Result {
    product := NewProduct(name, price)
    product.Save()
    return c.Redirect("/products/%d", product.id)
}

func (c App) EditProduct(id, name string, price int) revel.Result {
    product := loadProduct(id)
    product.name = name
    product.price = price
    go cache.Set("product_"+id, product, 30*time.Minute)
    return c.Redirect("/products/%d", id)
}

func (c App) DeleteProduct(id string) revel.Result {
    product := loadProduct(id)
    product.Delete()
    go cache.Delete("product_"+id)
    return c.Redirect("/products")
}

Session 用法

緩存有一個全球性的key空間 - 使用它作為一個session存儲,調(diào)用方應(yīng)采用session UUID的優(yōu)點(diǎn),如下圖所示:

cache.Set(c.Session.Id(), products)

// 然后在隨后的請求中使用它
err := cache.Get(c.Session.Id(), &products)


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號