gitea源码

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // Copyright 2019 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package setting
  4. import (
  5. "strings"
  6. "time"
  7. "code.gitea.io/gitea/modules/log"
  8. )
  9. // Cache represents cache settings
  10. type Cache struct {
  11. Adapter string
  12. Interval int
  13. Conn string
  14. TTL time.Duration `ini:"ITEM_TTL"`
  15. }
  16. // CacheService the global cache
  17. var CacheService = struct {
  18. Cache `ini:"cache"`
  19. LastCommit struct {
  20. TTL time.Duration `ini:"ITEM_TTL"`
  21. CommitsCount int64
  22. } `ini:"cache.last_commit"`
  23. }{
  24. Cache: Cache{
  25. Adapter: "memory",
  26. Interval: 60,
  27. TTL: 16 * time.Hour,
  28. },
  29. LastCommit: struct {
  30. TTL time.Duration `ini:"ITEM_TTL"`
  31. CommitsCount int64
  32. }{
  33. TTL: 8760 * time.Hour,
  34. CommitsCount: 1000,
  35. },
  36. }
  37. // MemcacheMaxTTL represents the maximum memcache TTL
  38. const MemcacheMaxTTL = 30 * 24 * time.Hour
  39. func loadCacheFrom(rootCfg ConfigProvider) {
  40. sec := rootCfg.Section("cache")
  41. if err := sec.MapTo(&CacheService); err != nil {
  42. log.Fatal("Failed to map Cache settings: %v", err)
  43. }
  44. CacheService.Adapter = sec.Key("ADAPTER").In("memory", []string{"memory", "redis", "memcache", "twoqueue"})
  45. switch CacheService.Adapter {
  46. case "memory":
  47. case "redis", "memcache":
  48. CacheService.Conn = strings.Trim(sec.Key("HOST").String(), "\" ")
  49. case "twoqueue":
  50. CacheService.Conn = strings.TrimSpace(sec.Key("HOST").String())
  51. if CacheService.Conn == "" {
  52. CacheService.Conn = "50000"
  53. }
  54. default:
  55. log.Fatal("Unknown cache adapter: %s", CacheService.Adapter)
  56. }
  57. sec = rootCfg.Section("cache.last_commit")
  58. CacheService.LastCommit.CommitsCount = sec.Key("COMMITS_COUNT").MustInt64(1000)
  59. }
  60. // TTLSeconds returns the TTLSeconds or unix timestamp for memcache
  61. func (c Cache) TTLSeconds() int64 {
  62. if c.Adapter == "memcache" && c.TTL > MemcacheMaxTTL {
  63. return time.Now().Add(c.TTL).Unix()
  64. }
  65. return int64(c.TTL.Seconds())
  66. }
  67. // LastCommitCacheTTLSeconds returns the TTLSeconds or unix timestamp for memcache
  68. func LastCommitCacheTTLSeconds() int64 {
  69. if CacheService.Adapter == "memcache" && CacheService.LastCommit.TTL > MemcacheMaxTTL {
  70. return time.Now().Add(CacheService.LastCommit.TTL).Unix()
  71. }
  72. return int64(CacheService.LastCommit.TTL.Seconds())
  73. }