GO简单包一下缓存

ICacheQueryBase

type ICacheQueryBase  interface {
    GetCacheKey() string
}

  

CacheMiddleware

package entity_cache

import (
    "encoding/json"
    "errors"
    "github.com/coocood/freecache"
    "reflect"
)

type CacheCore   struct {
}

func (c *CacheCore) OnHit(key string) ([]byte, bool) {
    resp, err := LocalCache.Get([]byte(key))
    if err == freecache.ErrNotFound {
        return nil, false
    }
    if err != nil {
        //log
        return nil, false
    }

    return resp, true
}

func (c *CacheCore) Set(key string, data []byte, expireSeconds int) {
    err := LocalCache.Set([]byte(key), []byte(data), expireSeconds)
    if err != nil {
        //log
    }
}

type CacheMiddleware   struct {
}

func (c *CacheMiddleware) Query(query ICacheQueryBase, reload   func (query ICacheQueryBase) (  interface {}, error), refV   interface {}) error {
    cacheCore := CacheCore{}

    if cacheBytes, isHit := cacheCore.OnHit(query.GetCacheKey()); isHit {
        err := json.Unmarshal(cacheBytes, &refV)
        if err == nil {
            return nil
        }   else {
            //log
        }
    }

    resp, err := reload(query)
    if err != nil {
        return err
    }

    va := reflect.ValueOf(refV).Elem()
    if va.IsValid() {
        va.Set(reflect.ValueOf(resp))
    }   else {
        return errors.New(  "err type,refV must be pointer" )
    }

    respByte, err := json.Marshal(resp)
    if err != nil {
        //log
    }
    cacheCore.Set(query.GetCacheKey(), respByte, 60)

    return nil
}

Cache_test

type UserEntity struct {
	UserId   int64
	UserName string
}

type UserQuery struct {
	UserId int64
}

func (c UserQuery) GetCacheKey() string {
	idStr := strconv.FormatInt(c.UserId, 10)
	return "User" + idStr
}
func TestCache(t *testing.T) {
	Init()

	var userId int64 = 99
	query := UserQuery{
		UserId: userId,
	}

	var respV UserEntity

	medware := CacheMiddleware{}
	err := medware.Query(query, func(query ICacheQueryBase) (interface{}, error) {
		q := query.(UserQuery)
		return UserEntity{
			UserId:   q.UserId,
			UserName: "UUUUUUUUUUUUU",
		}, nil
	}, &respV)
	if err != nil {
		//
	}

	var respV2 UserEntity
	err = medware.Query(query, func(query ICacheQueryBase) (interface{}, error) {
		q := query.(UserQuery)
		return UserEntity{
			UserId:   q.UserId,
			UserName: "UUUUUUUUUUUUU",
		}, nil
	}, &respV2)
	if err != nil {
		//
	}

	fmt.Println(respV2)
}

  

 

posted @ 2022-08-30 13:08  FCmmmmmm  阅读(37)  评论(0编辑  收藏  举报