memory.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. // Copyright 2014 beego Author. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package cache
  15. import (
  16. "encoding/json"
  17. "errors"
  18. "sync"
  19. "time"
  20. )
  21. var (
  22. // DefaultEvery means the clock time of recycling the expired cache items in memory.
  23. DefaultEvery = 60 // 1 minute
  24. )
  25. // MemoryItem store memory cache item.
  26. type MemoryItem struct {
  27. val interface{}
  28. createdTime time.Time
  29. lifespan time.Duration
  30. }
  31. func (mi *MemoryItem) isExpire() bool {
  32. // 0 means forever
  33. if mi.lifespan == 0 {
  34. return false
  35. }
  36. return time.Now().Sub(mi.createdTime) > mi.lifespan
  37. }
  38. // MemoryCache is Memory cache adapter.
  39. // it contains a RW locker for safe map storage.
  40. type MemoryCache struct {
  41. sync.RWMutex
  42. dur time.Duration
  43. items map[string]*MemoryItem
  44. Every int // run an expiration check Every clock time
  45. }
  46. // NewMemoryCache returns a new MemoryCache.
  47. func NewMemoryCache() Cache {
  48. cache := MemoryCache{items: make(map[string]*MemoryItem)}
  49. return &cache
  50. }
  51. // Get cache from memory.
  52. // if non-existed or expired, return nil.
  53. func (bc *MemoryCache) Get(name string) interface{} {
  54. bc.RLock()
  55. defer bc.RUnlock()
  56. if itm, ok := bc.items[name]; ok {
  57. if itm.isExpire() {
  58. return nil
  59. }
  60. return itm.val
  61. }
  62. return nil
  63. }
  64. // GetMulti gets caches from memory.
  65. // if non-existed or expired, return nil.
  66. func (bc *MemoryCache) GetMulti(names []string) []interface{} {
  67. var rc []interface{}
  68. for _, name := range names {
  69. rc = append(rc, bc.Get(name))
  70. }
  71. return rc
  72. }
  73. // Put cache to memory.
  74. // if lifespan is 0, it will be forever till restart.
  75. func (bc *MemoryCache) Put(name string, value interface{}, lifespan time.Duration) error {
  76. bc.Lock()
  77. defer bc.Unlock()
  78. bc.items[name] = &MemoryItem{
  79. val: value,
  80. createdTime: time.Now(),
  81. lifespan: lifespan,
  82. }
  83. return nil
  84. }
  85. // Delete cache in memory.
  86. func (bc *MemoryCache) Delete(name string) error {
  87. bc.Lock()
  88. defer bc.Unlock()
  89. if _, ok := bc.items[name]; !ok {
  90. return errors.New("key not exist")
  91. }
  92. delete(bc.items, name)
  93. if _, ok := bc.items[name]; ok {
  94. return errors.New("delete key error")
  95. }
  96. return nil
  97. }
  98. // Incr increase cache counter in memory.
  99. // it supports int,int32,int64,uint,uint32,uint64.
  100. func (bc *MemoryCache) Incr(key string) error {
  101. bc.RLock()
  102. defer bc.RUnlock()
  103. itm, ok := bc.items[key]
  104. if !ok {
  105. return errors.New("key not exist")
  106. }
  107. switch itm.val.(type) {
  108. case int:
  109. itm.val = itm.val.(int) + 1
  110. case int32:
  111. itm.val = itm.val.(int32) + 1
  112. case int64:
  113. itm.val = itm.val.(int64) + 1
  114. case uint:
  115. itm.val = itm.val.(uint) + 1
  116. case uint32:
  117. itm.val = itm.val.(uint32) + 1
  118. case uint64:
  119. itm.val = itm.val.(uint64) + 1
  120. default:
  121. return errors.New("item val is not (u)int (u)int32 (u)int64")
  122. }
  123. return nil
  124. }
  125. // Decr decrease counter in memory.
  126. func (bc *MemoryCache) Decr(key string) error {
  127. bc.RLock()
  128. defer bc.RUnlock()
  129. itm, ok := bc.items[key]
  130. if !ok {
  131. return errors.New("key not exist")
  132. }
  133. switch itm.val.(type) {
  134. case int:
  135. itm.val = itm.val.(int) - 1
  136. case int64:
  137. itm.val = itm.val.(int64) - 1
  138. case int32:
  139. itm.val = itm.val.(int32) - 1
  140. case uint:
  141. if itm.val.(uint) > 0 {
  142. itm.val = itm.val.(uint) - 1
  143. } else {
  144. return errors.New("item val is less than 0")
  145. }
  146. case uint32:
  147. if itm.val.(uint32) > 0 {
  148. itm.val = itm.val.(uint32) - 1
  149. } else {
  150. return errors.New("item val is less than 0")
  151. }
  152. case uint64:
  153. if itm.val.(uint64) > 0 {
  154. itm.val = itm.val.(uint64) - 1
  155. } else {
  156. return errors.New("item val is less than 0")
  157. }
  158. default:
  159. return errors.New("item val is not int int64 int32")
  160. }
  161. return nil
  162. }
  163. // IsExist check cache exist in memory.
  164. func (bc *MemoryCache) IsExist(name string) bool {
  165. bc.RLock()
  166. defer bc.RUnlock()
  167. if v, ok := bc.items[name]; ok {
  168. return !v.isExpire()
  169. }
  170. return false
  171. }
  172. // ClearAll will delete all cache in memory.
  173. func (bc *MemoryCache) ClearAll() error {
  174. bc.Lock()
  175. defer bc.Unlock()
  176. bc.items = make(map[string]*MemoryItem)
  177. return nil
  178. }
  179. // StartAndGC start memory cache. it will check expiration in every clock time.
  180. func (bc *MemoryCache) StartAndGC(config string) error {
  181. var cf map[string]int
  182. json.Unmarshal([]byte(config), &cf)
  183. if _, ok := cf["interval"]; !ok {
  184. cf = make(map[string]int)
  185. cf["interval"] = DefaultEvery
  186. }
  187. dur := time.Duration(cf["interval"]) * time.Second
  188. bc.Every = cf["interval"]
  189. bc.dur = dur
  190. go bc.vaccuum()
  191. return nil
  192. }
  193. // check expiration.
  194. func (bc *MemoryCache) vaccuum() {
  195. if bc.Every < 1 {
  196. return
  197. }
  198. for {
  199. <-time.After(bc.dur)
  200. if bc.items == nil {
  201. return
  202. }
  203. for name := range bc.items {
  204. bc.itemExpired(name)
  205. }
  206. }
  207. }
  208. // itemExpired returns true if an item is expired.
  209. func (bc *MemoryCache) itemExpired(name string) bool {
  210. bc.Lock()
  211. defer bc.Unlock()
  212. itm, ok := bc.items[name]
  213. if !ok {
  214. return true
  215. }
  216. if itm.isExpire() {
  217. delete(bc.items, name)
  218. return true
  219. }
  220. return false
  221. }
  222. func init() {
  223. Register("memory", NewMemoryCache)
  224. }