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 1.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // Copyright 2017 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package cache
  4. import (
  5. "strconv"
  6. "time"
  7. "code.gitea.io/gitea/modules/setting"
  8. )
  9. var defaultCache StringCache
  10. // Init start cache service
  11. func Init() error {
  12. if defaultCache == nil {
  13. c, err := NewStringCache(setting.CacheService.Cache)
  14. if err != nil {
  15. return err
  16. }
  17. for i := 0; i < 10; i++ {
  18. if err = c.Ping(); err == nil {
  19. break
  20. }
  21. time.Sleep(time.Second)
  22. }
  23. if err != nil {
  24. return err
  25. }
  26. defaultCache = c
  27. }
  28. return nil
  29. }
  30. // GetCache returns the currently configured cache
  31. func GetCache() StringCache {
  32. return defaultCache
  33. }
  34. // GetString returns the key value from cache with callback when no key exists in cache
  35. func GetString(key string, getFunc func() (string, error)) (string, error) {
  36. if defaultCache == nil || setting.CacheService.TTL == 0 {
  37. return getFunc()
  38. }
  39. cached, exist := defaultCache.Get(key)
  40. if !exist {
  41. value, err := getFunc()
  42. if err != nil {
  43. return value, err
  44. }
  45. return value, defaultCache.Put(key, value, setting.CacheService.TTLSeconds())
  46. }
  47. return cached, nil
  48. }
  49. // GetInt64 returns key value from cache with callback when no key exists in cache
  50. func GetInt64(key string, getFunc func() (int64, error)) (int64, error) {
  51. s, err := GetString(key, func() (string, error) {
  52. v, err := getFunc()
  53. return strconv.FormatInt(v, 10), err
  54. })
  55. if err != nil {
  56. return 0, err
  57. }
  58. if s == "" {
  59. return 0, nil
  60. }
  61. return strconv.ParseInt(s, 10, 64)
  62. }
  63. // Remove key from cache
  64. func Remove(key string) {
  65. if defaultCache == nil {
  66. return
  67. }
  68. _ = defaultCache.Delete(key)
  69. }