package myRedis import ( "bytes" "encoding/gob" "encoding/json" "time" ) const ( SerializerNot = "" SerializerJson = "json" SerializerGob = "gob" ) type CacheGetterFunc func() interface{} type SimpleCache struct { Operation *StringOperation Expire time.Duration CacheGetter CacheGetterFunc Serializer string //序列化方式 } func NewSimpleCache(operation *StringOperation, expire time.Duration, serializer string) *SimpleCache { return &SimpleCache{Operation: operation, Expire: expire, Serializer: serializer} } func (t *SimpleCache) SetCacheGetterFunc(f CacheGetterFunc) *SimpleCache { t.CacheGetter = f return t } // 设置缓存 func (t *SimpleCache) SetCache(key string, value interface{}) { //if t.Serializer == SerializerNot { //} if t.Serializer == SerializerJson { f := func() string { j, e := json.Marshal(value) if e != nil { return e.Error() } else { return string(j) } } t.Operation.Set(key, f(), WithExpire(t.Expire)).Unwrap() } else if t.Serializer == SerializerGob { f := func() string { var buf = &bytes.Buffer{} enc := gob.NewEncoder(buf) if err := enc.Encode(value); err != nil { return "" } return buf.String() } t.Operation.Set(key, f(), WithExpire(t.Expire)).Unwrap() } else { t.Operation.Set(key, value, WithExpire(t.Expire)).Unwrap() } } func (t *SimpleCache) GetCache(key string) (ret interface{}) { //如果没有设置的话 if t.CacheGetter == nil { panic("没有设置CacheGetter") } if t.Serializer == SerializerNot { } if t.Serializer == SerializerJson { f := func() string { j, e := json.Marshal(t.CacheGetter()) if e != nil { return e.Error() } else { return string(j) } } ret = t.Operation.Get(key).UnwrapOrElse(func() string { data := f() t.Operation.Set(key, data, WithExpire(t.Expire)).Unwrap() return data }) } if t.Serializer == SerializerGob { f := func() string { var buf = &bytes.Buffer{} enc := gob.NewEncoder(buf) if err := enc.Encode(t.CacheGetter()); err != nil { return "" } return buf.String() } ret = t.Operation.Get(key).UnwrapOrElse(func() string { data := f() t.Operation.Set(key, data, WithExpire(t.Expire)).Unwrap() return data }) } return } func (t *SimpleCache) DelCache(key string) int64 { return t.Operation.Del(key).UnwrapOr(0) } func (t *SimpleCache) GetCacheForObject(key string, obj interface{}) interface{} { ret := t.GetCache(key) if ret == nil { return nil } if t.Serializer == SerializerNot { obj = ret } else if t.Serializer == SerializerJson { err := json.Unmarshal([]byte(ret.(string)), obj) if err != nil { return nil } } else if t.Serializer == SerializerGob { var buf = &bytes.Buffer{} buf.WriteString(ret.(string)) dec := gob.NewDecoder(buf) if dec.Decode(obj) != nil { return nil } } return nil }