You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

cache.go 2.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. // Copyright 2017 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package cache
  5. import (
  6. "fmt"
  7. "strconv"
  8. "code.gitea.io/gitea/modules/setting"
  9. mc "github.com/go-macaron/cache"
  10. )
  11. var conn mc.Cache
  12. // NewContext start cache service
  13. func NewContext() error {
  14. if setting.CacheService == nil || conn != nil {
  15. return nil
  16. }
  17. var err error
  18. conn, err = mc.NewCacher(setting.CacheService.Adapter, mc.Options{
  19. Adapter: setting.CacheService.Adapter,
  20. AdapterConfig: setting.CacheService.Conn,
  21. Interval: setting.CacheService.Interval,
  22. })
  23. return err
  24. }
  25. // GetInt returns key value from cache with callback when no key exists in cache
  26. func GetInt(key string, getFunc func() (int, error)) (int, error) {
  27. if conn == nil || setting.CacheService.TTL == 0 {
  28. return getFunc()
  29. }
  30. if !conn.IsExist(key) {
  31. var (
  32. value int
  33. err error
  34. )
  35. if value, err = getFunc(); err != nil {
  36. return value, err
  37. }
  38. conn.Put(key, value, int64(setting.CacheService.TTL.Seconds()))
  39. }
  40. switch value := conn.Get(key).(type) {
  41. case int:
  42. return value, nil
  43. case string:
  44. v, err := strconv.Atoi(value)
  45. if err != nil {
  46. return 0, err
  47. }
  48. return v, nil
  49. default:
  50. return 0, fmt.Errorf("Unsupported cached value type: %v", value)
  51. }
  52. }
  53. // GetInt64 returns key value from cache with callback when no key exists in cache
  54. func GetInt64(key string, getFunc func() (int64, error)) (int64, error) {
  55. if conn == nil || setting.CacheService.TTL == 0 {
  56. return getFunc()
  57. }
  58. if !conn.IsExist(key) {
  59. var (
  60. value int64
  61. err error
  62. )
  63. if value, err = getFunc(); err != nil {
  64. return value, err
  65. }
  66. conn.Put(key, value, int64(setting.CacheService.TTL.Seconds()))
  67. }
  68. switch value := conn.Get(key).(type) {
  69. case int64:
  70. return value, nil
  71. case string:
  72. v, err := strconv.ParseInt(value, 10, 64)
  73. if err != nil {
  74. return 0, err
  75. }
  76. return v, nil
  77. default:
  78. return 0, fmt.Errorf("Unsupported cached value type: %v", value)
  79. }
  80. }
  81. // Remove key from cache
  82. func Remove(key string) {
  83. if conn == nil {
  84. return
  85. }
  86. conn.Delete(key)
  87. }