在 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 方法,會進(jìn)入到匿名結(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)文章
10個現(xiàn)代網(wǎng)站開發(fā)必備的Go軟件包工具盤點(diǎn)
這篇文章主要為大家介紹了10個現(xiàn)代網(wǎng)站開發(fā)必備的Go軟件包,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-10-10
Go中阻塞以及非阻塞操作實現(xiàn)(Goroutine和main Goroutine)
本文主要介紹了Go中阻塞以及非阻塞操作實現(xiàn)(Goroutine和main Goroutine),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-05-05
Go語言實現(xiàn)一個Http?Server框架(一)?http庫的使用
本文主要介紹用Go語言實現(xiàn)一個Http?Server框架中對http庫的基本使用說明,文中有詳細(xì)的代碼示例,感興趣的同學(xué)可以借鑒一下2023-04-04

