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.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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 "gitea.com/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. err = conn.Put(key, value, int64(setting.CacheService.TTL.Seconds()))
  39. if err != nil {
  40. return 0, err
  41. }
  42. }
  43. switch value := conn.Get(key).(type) {
  44. case int:
  45. return value, nil
  46. case string:
  47. v, err := strconv.Atoi(value)
  48. if err != nil {
  49. return 0, err
  50. }
  51. return v, nil
  52. default:
  53. return 0, fmt.Errorf("Unsupported cached value type: %v", value)
  54. }
  55. }
  56. // GetInt64 returns key value from cache with callback when no key exists in cache
  57. func GetInt64(key string, getFunc func() (int64, error)) (int64, error) {
  58. if conn == nil || setting.CacheService.TTL == 0 {
  59. return getFunc()
  60. }
  61. if !conn.IsExist(key) {
  62. var (
  63. value int64
  64. err error
  65. )
  66. if value, err = getFunc(); err != nil {
  67. return value, err
  68. }
  69. err = conn.Put(key, value, int64(setting.CacheService.TTL.Seconds()))
  70. if err != nil {
  71. return 0, err
  72. }
  73. }
  74. switch value := conn.Get(key).(type) {
  75. case int64:
  76. return value, nil
  77. case string:
  78. v, err := strconv.ParseInt(value, 10, 64)
  79. if err != nil {
  80. return 0, err
  81. }
  82. return v, nil
  83. default:
  84. return 0, fmt.Errorf("Unsupported cached value type: %v", value)
  85. }
  86. }
  87. // Remove key from cache
  88. func Remove(key string) {
  89. if conn == nil {
  90. return
  91. }
  92. _ = conn.Delete(key)
  93. }