在 Golang 中實現(xiàn) Cache::remember 方法詳解
項目需要把部分代碼移植到 Golang , 之前用 Laravel 封裝的寫起來很舒服,在 Golang 里只能自動動手實現(xiàn).
一開始想的是使用 interface 實現(xiàn),但是遇到了一個坑, Golang 里的組合是一個虛假的繼承
package main import "fmt" type Person interface { Say() Name() } type Parent struct { } func (s *Parent) Say() { fmt.Println("i am " + s.Name()) } func (s *Parent) Name() string { return "parent" } type Child struct { Parent } func (s *Child) Name() string { return "child" } type Child1 struct { Parent } func main() { var c Child // i am parent c.Say() var c1 Child1 // i am parent c1.Say() }
- 如上 c.say() 代碼,在別的語言里應(yīng)該是輸出 i am child 才對, 而 Golang 不一樣,查了一下 Golang 的資料才能理解 https://golang.org/ref/spec#Selectors
- 大致意思是說,通過 x.f 調(diào)用 f 方法或者屬性時,從當(dāng)前或者嵌套匿名結(jié)構(gòu)體由淺到深的去調(diào)用,而不會去尋找上級
- 比如 child1 沒有 Say 方法,會進入到匿名結(jié)構(gòu)體 Parent 找到 Say 方法,然后調(diào)用
- 而 child 也沒有 Say 方法,同樣去調(diào)用 Parent 的 Say 方法,這時候 Say 是通過 Parent 調(diào)用的, 當(dāng)在 Say 里調(diào)用 s.Name 方法,并不能找到 child , 所以還是會調(diào)用到 Parent 的 Name 方法
- 然后自己整理和同事一起寫了大致的 remember 方法
import ( "context" "encoding/json" "fmt" "github.com/gin-gonic/gin" "time" ) // redis 操作已經(jīng)簡化 func CacheGet(c context.Context, t interface{}, cacheKey string, callQuery func() error) error { // 此處通過 redis 獲取數(shù)據(jù), 如果存在數(shù)據(jù), 那么直接返回 dataBytes, err := redis.Get(c, cacheKey).Bytes() if err == nil { if err := json.Unmarshal(dataBytes, t); err == nil { return nil } } // 當(dāng) redis 沒有數(shù)據(jù), 那么調(diào)用此方法修改 t, if err := callQuery(); err != nil { return err } // 這里把修改之后的 t 存儲到 redis, 下次使用便可以使用緩存 dataBytes, err = json.Marshal(t) if err == nil { redis.Set(c, cacheKey, dataBytes, time.Minute*30) } return nil } func handle(c *gin.Context) { var model models.User err := utils.CacheGet( c.Request.Context(), &model, fmt.Sprintf("cache_xxx:%s", c.Param("id")), func() error { return db.First(&model) }, ) }
到此這篇關(guān)于在 Golang 中實現(xiàn) Cache::remember 方法的文章就介紹到這了,更多相關(guān)Golang實現(xiàn) Cache::remember 內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Golang中make與new使用區(qū)別小結(jié)
Go語言中new和make是內(nèi)建的兩個函數(shù),主要用來創(chuàng)建分配類型內(nèi)存,本文主要給大家介紹了Go語言中函數(shù)new與make的使用和區(qū)別,具有一定的參考價值,感興趣的可以了解一下2024-01-01詳解如何使用Golang操作MongoDB數(shù)據(jù)庫
在現(xiàn)代開發(fā)中,數(shù)據(jù)存儲是一個至關(guān)重要的環(huán)節(jié),MongoDB作為一種NoSQL數(shù)據(jù)庫,提供了強大的功能和靈活的數(shù)據(jù)模型,與Golang的高性能和并發(fā)性能非常契合,本文將探討Golang與MongoDB的完美組合,介紹如何使用Golang操作MongoDB數(shù)據(jù)庫,需要的朋友可以參考下2023-11-11如何使用?Go?和?Excelize?構(gòu)建電子表格
這篇文章主要介紹了如何使用Go和Excelize構(gòu)建電子表格,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-09-09golang gorm 計算字段和獲取sum()值的實現(xiàn)
這篇文章主要介紹了golang gorm 計算字段和獲取sum()值的實現(xiàn)操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-12-12Go?實現(xiàn)?WebSockets和什么是?WebSockets
這篇文章主要介紹了Go?實現(xiàn)?WebSockets和什么是?WebSockets,WebSockets?是構(gòu)建實時應(yīng)用程序的第一大解決方案,在線游戲、即時通訊、跟蹤應(yīng)用程序等,下文相關(guān)內(nèi)容介紹需要的小伙伴可以參考一下2022-04-04