code.gitea.io/gitea@v1.22.3/modules/cache/cache.go (about)

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