github.com/qjfoidnh/BaiduPCS-Go@v0.0.0-20231011165705-caa18a3765f3/baidupcs/expires/cachemap/utils.go (about)

     1  package cachemap
     2  
     3  import (
     4  	"github.com/qjfoidnh/BaiduPCS-Go/baidupcs/expires"
     5  )
     6  
     7  type (
     8  	OpFunc          func() expires.DataExpires
     9  	OpFuncWithError func() (expires.DataExpires, error)
    10  )
    11  
    12  func (cm *CacheOpMap) CacheOperation(op string, key interface{}, opFunc OpFunc) (data expires.DataExpires) {
    13  	var (
    14  		cache = cm.LazyInitCachePoolOp(op)
    15  		ok    bool
    16  	)
    17  
    18  	cache.LockKey(key)
    19  	defer cache.UnlockKey(key)
    20  	data, ok = cache.Load(key)
    21  	if !ok {
    22  		data = opFunc()
    23  		if data != nil {
    24  			cache.Store(key, data)
    25  		}
    26  		return
    27  	}
    28  
    29  	return
    30  }
    31  
    32  func (cm *CacheOpMap) CacheOperationWithError(op string, key interface{}, opFunc OpFuncWithError) (data expires.DataExpires, err error) {
    33  	var (
    34  		cache = cm.LazyInitCachePoolOp(op)
    35  		ok    bool
    36  	)
    37  
    38  	cache.LockKey(key)
    39  	defer cache.UnlockKey(key)
    40  	data, ok = cache.Load(key)
    41  	if !ok {
    42  		data, err = opFunc()
    43  		if err != nil {
    44  			return
    45  		}
    46  		if data == nil {
    47  			// 数据为空时也不存
    48  			return
    49  		}
    50  		cache.Store(key, data)
    51  	}
    52  
    53  	return
    54  }