查询缓存
gdb
支持对查询结果的缓存处理,常用于多读少写的查询缓存场景,并支持手动的缓存清理。需要注意的是,查询缓存仅支持链式操作,且在事务操作下不可用。
相关方法:
type CacheOption struct {
// Duration is the TTL for the cache.
// If the parameter `Duration` < 0, which means it clear the cache with given `Name`.
// If the parameter `Duration` = 0, which means it never expires.
// If the parameter `Duration` > 0, which means it expires after `Duration`.
Duration time.Duration
// Name is an optional unique name for the cache.
// The Name is used to bind a name to the cache, which means you can later control the cache
// like changing the `duration` or clearing the cache with specified Name.
Name string
// Force caches the query result whatever the result is nil or not.
// It is used to avoid Cache Penetration.
Force bool
}
// Cache sets the cache feature for the model. It caches the result of the sql, which means
// if there's another same sql request, it just reads and returns the result from cache, it
// but not committed and executed into the database.
//
// Note that, the cache feature is disabled if the model is performing select statement
// on a transaction.
func (m *Model) Cache(option CacheOption) *Model
缓存管理
缓存对象
ORM
对象默认情况下提供了缓存管理对象,该缓存对象类型为 *gcache.Cache
,也就是说同时也支持 *gcache.Cache
的所有特性。可以通过 GetCache() *gcache.Cache
接口方法获得该缓存对象,并通过返回的对象实现自定义的各种缓存操作,例如: g.DB().GetCache().Keys()
。