cache.go 2.0 KB

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