GoFrame 鏈?zhǔn)讲僮?查詢緩存

2022-04-02 10:50 更新

查詢緩存

?gdb?支持對查詢結(jié)果的緩存處理,常用于多讀少寫的查詢緩存場景,并支持手動的緩存清理。需要注意的是,查詢緩存僅支持鏈?zhǔn)讲僮?,且在事?wù)操作下不可用。

相關(guān)方法:

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?對象默認(rèn)情況下提供了緩存管理對象,該緩存對象類型為?*gcache.Cache?,也就是說同時也支持?*gcache.Cache?的所有特性??梢酝ㄟ^?GetCache() *gcache.Cache? 接口方法獲得該緩存對象,并通過返回的對象實現(xiàn)自定義的各種緩存操作,例如:?g.DB().GetCache().Keys()?。

緩存適配(Redis緩存)

默認(rèn)情況下?ORM?的?*gcache.Cache?緩存對象提供的是單進程內(nèi)存緩存,雖然性能非常高效,但是只能在單進程內(nèi)使用。如果服務(wù)如果采用多節(jié)點部署,多節(jié)點之間的緩存可能會產(chǎn)生數(shù)據(jù)不一致的情況,因此大多數(shù)場景下我們都是通過?Redis?服務(wù)器來實現(xiàn)對數(shù)據(jù)庫查詢數(shù)據(jù)的緩存。?*gcache.Cache?對象采用了適配器設(shè)計模式,可以輕松實現(xiàn)從單進程內(nèi)存緩存切換為分布式的?Redis?緩存。使用示例:

redisCache := gcache.NewAdapterRedis(g.Redis())
g.DB().GetCache().SetAdapter(redisCache)

使用示例

數(shù)據(jù)表結(jié)構(gòu)

CREATE TABLE `user` (
  `uid` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(30) NOT NULL DEFAULT '' COMMENT '昵稱',
  `site` varchar(255) NOT NULL DEFAULT '' COMMENT '主頁',
  PRIMARY KEY (`uid`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

示例代碼

package main

import (
	"time"

	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gctx"
)

func main() {
	var (
		db  = g.DB()
		ctx = gctx.New()
	)

	// 開啟調(diào)試模式,以便于記錄所有執(zhí)行的SQL
	db.SetDebug(true)

	// 寫入測試數(shù)據(jù)
	_, err := db.Model("user").Ctx(ctx).Data(g.Map{
		"name": "john",
		"site": "https://goframe.org",
	}).Insert()

	// 執(zhí)行2次查詢并將查詢結(jié)果緩存1小時,并可執(zhí)行緩存名稱(可選)
	for i := 0; i < 2; i++ {
		r, _ := db.Model("user").Ctx(ctx).Cache(gdb.CacheOption{
			Duration: time.Hour,
			Name:     "vip-user",
			Force:    false,
		}).Where("uid", 1).One()
		g.Log().Debug(ctx, r.Map())
	}

	// 執(zhí)行更新操作,并清理指定名稱的查詢緩存
	_, err = db.Model("user").Ctx(ctx).Cache(gdb.CacheOption{
		Duration: -1,
		Name:     "vip-user",
		Force:    false,
	}).Data(gdb.Map{"name": "smith"}).Where("uid", 1).Update()
	if err != nil {
		g.Log().Fatal(ctx, err)
	}

	// 再次執(zhí)行查詢,啟用查詢緩存特性
	r, _ := db.Model("user").Ctx(ctx).Cache(gdb.CacheOption{
		Duration: time.Hour,
		Name:     "vip-user",
		Force:    false,
	}).Where("uid", 1).One()
	g.Log().Debug(ctx, r.Map())
}

執(zhí)行后輸出結(jié)果為(測試表數(shù)據(jù)結(jié)構(gòu)僅供示例參考):

2022-02-08 17:36:19.817 [DEBU] {c0424c75f1c5d116d0df0f7197379412} {"name":"john","site":"https://goframe.org","uid":1} 
2022-02-08 17:36:19.817 [DEBU] {c0424c75f1c5d116d0df0f7197379412} {"name":"john","site":"https://goframe.org","uid":1} 
2022-02-08 17:36:19.817 [DEBU] {c0424c75f1c5d116d0df0f7197379412} [  0 ms] [default] [rows:1  ] UPDATE `user` SET `name`='smith' WHERE `uid`=1 
2022-02-08 17:36:19.818 [DEBU] {c0424c75f1c5d116d0df0f7197379412} [  1 ms] [default] [rows:1  ] SELECT * FROM `user` WHERE `uid`=1 LIMIT 1 
2022-02-08 17:36:19.818 [DEBU] {c0424c75f1c5d116d0df0f7197379412} {"name":"smith","site":"https://goframe.org","uid":1}

可以看到:

為了方便展示緩存效果,這里開啟了數(shù)據(jù)?debug?特性,當(dāng)有任何的?SQL?操作時將會輸出到終端。

執(zhí)行兩次?One?方法數(shù)據(jù)查詢,第一次走了?SQL?查詢,第二次直接使用到了緩存,?SQL?沒有提交到數(shù)據(jù)庫執(zhí)行,因此這里只打印了一條查詢?SQL?,并且兩次查詢的結(jié)果也是一致的。

注意這里為該查詢的緩存設(shè)置了一個自定義的名稱?vip-user?,以便于后續(xù)清空更新緩存。如果緩存不需要清理,那么可以不用設(shè)置緩存名稱。

當(dāng)執(zhí)行?Update?更新操作時,同時根據(jù)名稱清空指定的緩存。

隨后再執(zhí)行?One?方法數(shù)據(jù)查詢,這時重新緩存新的數(shù)據(jù)。


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

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號