golang实现laravel的cache remember方法

怀念laravel的缓存,太方便了,用golang实现一下

安利一下这个包 gookit/cache


type Cache interface {
	// basic operation
	Has(key string) bool
	Get(key string) interface{}
	Set(key string, val interface{}, ttl time.Duration) (err error)
	Del(key string) error
	// multi operation
	GetMulti(keys []string) map[string]interface{}
	SetMulti(values map[string]interface{}, ttl time.Duration) (err error)
	DelMulti(keys []string) error
	// clear and close
	Clear() error
	Close() error
}

这个包通过适配各种常用的缓存驱动来提供统一的封装好的缓存操作方法。切换驱动只需要一行代码就行。

func Remember(ctx context.Context, pointer interface{}, key string, ttl time.Duration, cb func() error) error {
	if cache.Has(key) {
	    //如果缓存有值,则反序列化
		return Json.Unmarshal(cache.Get(key).([]byte), pointer)
	} else {
	    //如果没有值,调用callback,
		err := cb()
		if err != nil {
			return err
		}
		//序列化值后存入缓存
		b, err := Json.Marshal(pointer)
		if err != nil {
			return err
		}
		return cache.Set(key, b, ttl)
	}
}

//使用

func test (){
	var cate models.Category
    //这里检查缓存有没有这个模型,如果没有就去数据库里查询并存入缓存
    err := util.Remember(e.Request().Context(), &cate, fmt.Sprintf("cate:%d", id), time.Second*86400, func() error {
	    DB.Model(&models.Category{}).With("Children").Find(&cate, id)
		return nil
	})
}