github.com/iikira/iikira-go-utils@v0.0.0-20230610031953-f2cb11cde33a/utils/expires/cachemap/utils.go (about)

     1  package cachemap
     2  
     3  import (
     4  	"github.com/iikira/iikira-go-utils/utils/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  		if opFunc == nil {
    23  			return
    24  		}
    25  		data = opFunc()
    26  		if data != nil {
    27  			cache.Store(key, data)
    28  		}
    29  		return
    30  	}
    31  
    32  	return
    33  }
    34  
    35  func (cm *CacheOpMap) CacheOperationWithError(op string, key interface{}, opFunc OpFuncWithError) (data expires.DataExpires, err error) {
    36  	var (
    37  		cache = cm.LazyInitCachePoolOp(op)
    38  		ok    bool
    39  	)
    40  
    41  	cache.LockKey(key)
    42  	defer cache.UnlockKey(key)
    43  	data, ok = cache.Load(key)
    44  	if !ok {
    45  		if opFunc == nil {
    46  			return
    47  		}
    48  		data, err = opFunc()
    49  		if err != nil {
    50  			return
    51  		}
    52  		if data == nil {
    53  			// 数据为空时也不存
    54  			return
    55  		}
    56  		cache.Store(key, data)
    57  	}
    58  
    59  	return
    60  }