github.com/tickstep/library-go@v0.1.1/expires/cachemap/cacheunit.go (about)

     1  package cachemap
     2  
     3  import (
     4  	"github.com/tickstep/library-go/expires"
     5  	"sync"
     6  )
     7  
     8  type (
     9  	CacheUnit interface {
    10  		Delete(key interface{})
    11  		Load(key interface{}) (value expires.DataExpires, ok bool)
    12  		LoadOrStore(key interface{}, value expires.DataExpires) (actual expires.DataExpires, loaded bool)
    13  		Range(f func(key interface{}, value expires.DataExpires) bool)
    14  		Store(key interface{}, value expires.DataExpires)
    15  		LockKey(key interface{})
    16  		UnlockKey(key interface{})
    17  	}
    18  
    19  	cacheUnit struct {
    20  		unit   sync.Map
    21  		keyMap sync.Map
    22  	}
    23  )
    24  
    25  func (cu *cacheUnit) Delete(key interface{}) {
    26  	cu.unit.Delete(key)
    27  	cu.keyMap.Delete(key)
    28  }
    29  
    30  func (cu *cacheUnit) Load(key interface{}) (value expires.DataExpires, ok bool) {
    31  	val, ok := cu.unit.Load(key)
    32  	if !ok {
    33  		return nil, ok
    34  	}
    35  	exp := val.(expires.DataExpires)
    36  	if exp.IsExpires() {
    37  		cu.unit.Delete(key)
    38  		return nil, false
    39  	}
    40  	return exp, ok
    41  }
    42  
    43  func (cu *cacheUnit) Range(f func(key interface{}, value expires.DataExpires) bool) {
    44  	cu.unit.Range(func(k, val interface{}) bool {
    45  		exp := val.(expires.DataExpires)
    46  		if exp.IsExpires() {
    47  			cu.unit.Delete(k)
    48  			return true
    49  		}
    50  		return f(k, val.(expires.DataExpires))
    51  	})
    52  }
    53  
    54  func (cu *cacheUnit) LoadOrStore(key interface{}, value expires.DataExpires) (actual expires.DataExpires, loaded bool) {
    55  	ac, loaded := cu.unit.LoadOrStore(key, value)
    56  	exp := ac.(expires.DataExpires)
    57  	if exp.IsExpires() {
    58  		cu.unit.Delete(key)
    59  		return nil, false
    60  	}
    61  	return exp, loaded
    62  }
    63  
    64  func (cu *cacheUnit) Store(key interface{}, value expires.DataExpires) {
    65  	if value.IsExpires() {
    66  		return
    67  	}
    68  	cu.unit.Store(key, value)
    69  }
    70  
    71  func (cu *cacheUnit) LockKey(key interface{}) {
    72  	muItf, _ := cu.keyMap.LoadOrStore(key, &sync.Mutex{})
    73  	mu := muItf.(*sync.Mutex)
    74  	mu.Lock()
    75  }
    76  
    77  func (cu *cacheUnit) UnlockKey(key interface{}) {
    78  	muItf, _ := cu.keyMap.LoadOrStore(key, &sync.Mutex{})
    79  	mu := muItf.(*sync.Mutex)
    80  	mu.Unlock()
    81  }