溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

在Golang中怎么實(shí)現(xiàn)Cache::remember

發(fā)布時間:2021-03-30 14:11:20 來源:億速云 閱讀:173 作者:小新 欄目:開發(fā)技術(shù)

這篇文章主要介紹在Golang中怎么實(shí)現(xiàn)Cache::remember,文中介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們一定要看完!

項(xiàng)目需要把部分代碼移植到 Golang , 之前用 Laravel 封裝的寫起來很舒服,在 Golang 里只能自動動手實(shí)現(xiàn).
一開始想的是使用 interface 實(shí)現(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)
  },
 )
}

以上是“在Golang中怎么實(shí)現(xiàn)Cache::remember”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI