github.com/insionng/yougam@v0.0.0-20170714101924-2bc18d833463/libraries/go-xorm/core/cache.go (about) 1 package core 2 3 import ( 4 "errors" 5 "fmt" 6 "time" 7 "bytes" 8 "encoding/gob" 9 ) 10 11 const ( 12 // default cache expired time 13 CacheExpired = 60 * time.Minute 14 // not use now 15 CacheMaxMemory = 256 16 // evey ten minutes to clear all expired nodes 17 CacheGcInterval = 10 * time.Minute 18 // each time when gc to removed max nodes 19 CacheGcMaxRemoved = 20 20 ) 21 22 var ( 23 ErrCacheMiss = errors.New("xorm/cache: key not found.") 24 ErrNotStored = errors.New("xorm/cache: not stored.") 25 ) 26 27 // CacheStore is a interface to store cache 28 type CacheStore interface { 29 // key is primary key or composite primary key 30 // value is struct's pointer 31 // key format : <tablename>-p-<pk1>-<pk2>... 32 Put(key string, value interface{}) error 33 Get(key string) (interface{}, error) 34 Del(key string) error 35 } 36 37 // Cacher is an interface to provide cache 38 // id format : u-<pk1>-<pk2>... 39 type Cacher interface { 40 GetIds(tableName, sql string) interface{} 41 GetBean(tableName string, id string) interface{} 42 PutIds(tableName, sql string, ids interface{}) 43 PutBean(tableName string, id string, obj interface{}) 44 DelIds(tableName, sql string) 45 DelBean(tableName string, id string) 46 ClearIds(tableName string) 47 ClearBeans(tableName string) 48 } 49 50 func encodeIds(ids []PK) (string, error) { 51 buf := new(bytes.Buffer) 52 enc := gob.NewEncoder(buf) 53 err := enc.Encode(ids) 54 55 return buf.String(), err 56 } 57 58 59 func decodeIds(s string) ([]PK, error) { 60 pks := make([]PK, 0) 61 62 dec := gob.NewDecoder(bytes.NewBufferString(s)) 63 err := dec.Decode(&pks) 64 65 return pks, err 66 } 67 68 func GetCacheSql(m Cacher, tableName, sql string, args interface{}) ([]PK, error) { 69 bytes := m.GetIds(tableName, GenSqlKey(sql, args)) 70 if bytes == nil { 71 return nil, errors.New("Not Exist") 72 } 73 return decodeIds(bytes.(string)) 74 } 75 76 func PutCacheSql(m Cacher, ids []PK, tableName, sql string, args interface{}) error { 77 bytes, err := encodeIds(ids) 78 if err != nil { 79 return err 80 } 81 m.PutIds(tableName, GenSqlKey(sql, args), bytes) 82 return nil 83 } 84 85 func GenSqlKey(sql string, args interface{}) string { 86 return fmt.Sprintf("%v-%v", sql, args) 87 }