Revel provides a Cache library for server-side, temporary, low-latency storage. It is a good replacement for frequent database access to slowly changing data. It could also be used for implementing user sessions, if for example the cookie-based sessions are insufficient.
Implementations
The Cache may be configured to be backed by one of the following implementations:
- a list of memcached hosts
- a single redis host
- the ‘in-memory’ implementation. Note the in memory stores the object in memory
and returns the same object when you
Get
it (if available). This means that updating an object retrieved from the cache will update the stored cache object as well.
Expiration
Cache items are set with an expiration time, in one of three forms:
- a time.Duration
cache.DefaultExpiryTime
- the application-wide default expiration time, one hour by default (see cache config)cache.ForEverNeverExpiry
- will cause the item to never expire
Serialization
The Cache getters and setters automatically serialize values for callers, to and from any type, with the exception of the inmemory model which stores and returns the object verbatim. It uses the following mechanisms:
- If the value is already of type
[]byte
, the data is not touched - If the value is of any integer type, it is stored as the ASCII representation
- Otherwise, the value is encoded using encoding/gob
Configuration
Configure the cache using these keys in conf/app.conf
:
cache.expires
- a string accepted by
time.ParseDuration
to specify the default expiration duration. (default 1 hour)
- a string accepted by
cache.memcached
- a boolean indicating whether or not memcached should be
used. (default
false
)
- a boolean indicating whether or not memcached should be
used. (default
cache.redis
- a boolean indicating whether or not redis should be
used. (default
false
)
- a boolean indicating whether or not redis should be
used. (default
cache.hosts
- a comma separated list of hosts to use as backends. If the backend is Redis, then only the first host in this list will be used.
Cache Example
Here’s an example of the common operations. Note that callers may invoke cache operations in a new goroutine if they do not require the result of the invocation to process the request.
Session usage
The Cache has a global key space. To use it as a session store, callers should take advantage of the session’s UUID, as shown below: