github.com/sohaha/zlsgo@v1.7.13-0.20240501141223-10dd1a906f76/zcache/item.go (about)

     1  package zcache
     2  
     3  import (
     4  	"sync"
     5  	"time"
     6  
     7  	"github.com/sohaha/zlsgo/ztime"
     8  )
     9  
    10  // Item Item
    11  type Item struct {
    12  	createdTime    time.Time
    13  	accessedTime   time.Time
    14  	data           interface{}
    15  	deleteCallback func(key string) bool
    16  	key            string
    17  	lifeSpan       time.Duration
    18  	accessCount    int64
    19  	sync.RWMutex
    20  	intervalLifeSpan bool
    21  }
    22  
    23  // NewCacheItem NewCacheItem
    24  func NewCacheItem(key string, data interface{}, lifeSpan time.Duration) *Item {
    25  	t := ztime.UnixMicro(ztime.Clock())
    26  	return &Item{
    27  		key:              key,
    28  		lifeSpan:         lifeSpan,
    29  		createdTime:      t,
    30  		accessedTime:     t,
    31  		accessCount:      0,
    32  		intervalLifeSpan: false,
    33  		deleteCallback:   nil,
    34  		data:             data,
    35  	}
    36  }
    37  
    38  func (item *Item) keepAlive() {
    39  	item.Lock()
    40  	item.accessedTime = ztime.UnixMicro(ztime.Clock())
    41  	item.accessCount++
    42  	item.Unlock()
    43  }
    44  
    45  // LifeSpan LifeSpan
    46  func (item *Item) LifeSpan() time.Duration {
    47  	return item.lifeSpan
    48  }
    49  
    50  // LifeSpan LifeSpan
    51  func (item *Item) IntervalLifeSpan() bool {
    52  	return item.intervalLifeSpan
    53  }
    54  
    55  // LifeSpanUint LifeSpanUint
    56  func (item *Item) LifeSpanUint() uint {
    57  	return uint(item.lifeSpan / time.Second)
    58  }
    59  
    60  // AccessedTime AccessedTime
    61  func (item *Item) AccessedTime() time.Time {
    62  	item.RLock()
    63  	defer item.RUnlock()
    64  	return item.accessedTime
    65  }
    66  
    67  // CreatedTime CreatedTime
    68  func (item *Item) CreatedTime() time.Time {
    69  	return item.createdTime
    70  }
    71  
    72  // RemainingLife RemainingLife
    73  func (item *Item) RemainingLife() time.Duration {
    74  	if item.lifeSpan == 0 {
    75  		return 0
    76  	}
    77  	return time.Until(item.createdTime.Add(item.lifeSpan))
    78  }
    79  
    80  // AccessCount AccessCount
    81  func (item *Item) AccessCount() int64 {
    82  	item.RLock()
    83  	defer item.RUnlock()
    84  	return item.accessCount
    85  }
    86  
    87  // Key item key
    88  func (item *Item) Key() interface{} {
    89  	return item.key
    90  }
    91  
    92  // Data data
    93  func (item *Item) Data() interface{} {
    94  	item.RLock()
    95  	defer item.RUnlock()
    96  	return item.data
    97  }
    98  
    99  // SetDeleteCallback SetDeleteCallback
   100  func (item *Item) SetDeleteCallback(fn func(key string) bool) {
   101  	item.Lock()
   102  	item.deleteCallback = fn
   103  	item.Unlock()
   104  }