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.

72 lines
1.6 KiB

  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. "code.gitea.io/gitea/modules/setting"
  7. mc "github.com/go-macaron/cache"
  8. )
  9. var conn mc.Cache
  10. // NewContext start cache service
  11. func NewContext() error {
  12. if setting.CacheService == nil || conn != nil {
  13. return nil
  14. }
  15. var err error
  16. conn, err = mc.NewCacher(setting.CacheService.Adapter, mc.Options{
  17. Adapter: setting.CacheService.Adapter,
  18. AdapterConfig: setting.CacheService.Conn,
  19. Interval: setting.CacheService.Interval,
  20. })
  21. return err
  22. }
  23. // GetInt returns key value from cache with callback when no key exists in cache
  24. func GetInt(key string, getFunc func() (int, error)) (int, error) {
  25. if conn == nil || setting.CacheService.TTL == 0 {
  26. return getFunc()
  27. }
  28. if !conn.IsExist(key) {
  29. var (
  30. value int
  31. err error
  32. )
  33. if value, err = getFunc(); err != nil {
  34. return value, err
  35. }
  36. conn.Put(key, value, int64(setting.CacheService.TTL.Seconds()))
  37. }
  38. return conn.Get(key).(int), nil
  39. }
  40. // GetInt64 returns key value from cache with callback when no key exists in cache
  41. func GetInt64(key string, getFunc func() (int64, error)) (int64, error) {
  42. if conn == nil || setting.CacheService.TTL == 0 {
  43. return getFunc()
  44. }
  45. if !conn.IsExist(key) {
  46. var (
  47. value int64
  48. err error
  49. )
  50. if value, err = getFunc(); err != nil {
  51. return value, err
  52. }
  53. conn.Put(key, value, int64(setting.CacheService.TTL.Seconds()))
  54. }
  55. return conn.Get(key).(int64), nil
  56. }
  57. // Remove key from cache
  58. func Remove(key string) {
  59. if conn == nil {
  60. return
  61. }
  62. conn.Delete(key)
  63. }