cache.go 2.0 KB

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