mem_cache.go 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package common
  2. import (
  3. "errors"
  4. "time"
  5. "github.com/patrickmn/go-cache"
  6. )
  7. var memCache *cache.Cache
  8. var licenseCache *cache.Cache
  9. func init() {
  10. memCache = cache.New(30*time.Second, 3*time.Second) //30秒钟超时,每3秒检查是否有需要超时清除
  11. licenseCache = cache.New(10*time.Minute, 1*time.Minute)
  12. }
  13. func SetMemCache(key string, value interface{}) {
  14. memCache.Set(key, value, cache.DefaultExpiration)
  15. }
  16. func GetMemCache(key string) (interface{}, error) {
  17. value, found := memCache.Get(key)
  18. if found {
  19. return value, nil
  20. }
  21. return nil, errors.New("Not Fount, key=" + key)
  22. }
  23. func GetMemCacheWithDelete(key string) (interface{}, error) {
  24. value, found := memCache.Get(key)
  25. if found {
  26. go memCache.Delete(key)
  27. return value, nil
  28. }
  29. return nil, errors.New("Not Fount, key=" + key)
  30. }
  31. func SetRspCode(url string, httpStatusCode int) {
  32. licenseCache.SetDefault(url, httpStatusCode)
  33. }
  34. func GetRspCode(url string) (int, bool) {
  35. if v, ok := licenseCache.Get(url); !ok {
  36. return 0, false
  37. } else {
  38. return v.(int), true
  39. }
  40. }