Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Revel cache Cache


May 15, 2021 Revel


Table of contents


Revel provides a server-side, temporary, low-latency repository. For frequent access to slowly changing data in the database, using caching is a good way, and it can also be used to implement user session (if cookie-based session is insufficient).

Refer to the cache interface

Expiration time

There are three expiration times for the cache:

  • time. Duration, specifying an expiration time.
  • cache.DEFAULT the default expiration time (1 hour).
  • cache.FOREVER never overdue.

Important: Callers cannot rely on what exists in the cache because the data is not persisted and all cached data is purged when restarted.

Serialization

The cache read and write interface automatically serializes any type of value for the caller. There are several ways:

  • In the []byte the data remains the same.
  • If it is an integer type, the data is saved as ASCII.
  • Other types, encoding/gob

Realize

The cache is configured in several ways:

Configuration

Configure app.conf

  • cache.expires - a string, time.ParseDuration specifying an expiration time (default 1 hour)
  • cache.memcached a Boolean value, whether to turn on the memcached cache (not on by default)
  • cache.redis - a Boolean value, whether to turn on the redis cache (not on by default)
  • cache.hosts - Cached list of hosts (multiple hosts separated by commas), cache.memcached turned on.

For example

The following is an example of a common operation. Note that if the result of the call is not required to handle the request, the caller can call the cache operation in the new goroutine.

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 usage

The cache has a global key space - using it as a session store, callers should take advantage of the benefits of session UUID, as shown in the following image:

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

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