github.com/unionj-cloud/go-doudou@v1.3.8-0.20221011095552-0088008e5b31/framework/cache/base.go (about)

     1  package cache
     2  
     3  import (
     4  	"golang.org/x/exp/rand"
     5  	"time"
     6  )
     7  
     8  type IStore interface {
     9  	Get(key interface{}) (value interface{}, ok bool)
    10  	Add(key, value interface{})
    11  	Remove(key interface{})
    12  }
    13  
    14  type base struct {
    15  	store  IStore
    16  	ttl    time.Duration
    17  	offset time.Duration
    18  	rand   *rand.Rand
    19  }
    20  
    21  func (l *base) Set(key string, data []byte) {
    22  	ttl := l.ttl
    23  	if l.offset > 0 {
    24  		ttl += time.Duration(l.rand.Int63n(int64(l.offset)))
    25  	}
    26  	l.store.Add(key, &Item{
    27  		Key:      key,
    28  		Value:    data,
    29  		ExpireAt: time.Now().Add(ttl),
    30  	})
    31  }
    32  
    33  func (l *base) Get(key string) ([]byte, bool) {
    34  	value, ok := l.store.Get(key)
    35  	if !ok {
    36  		return nil, false
    37  	}
    38  	item := value.(*Item)
    39  	if item.expired() {
    40  		l.store.Remove(key)
    41  		return nil, false
    42  	}
    43  	return item.Value.([]byte), true
    44  }
    45  
    46  func (l *base) Del(key string) {
    47  	l.store.Remove(key)
    48  }
    49  
    50  const maxOffset = 10 * time.Second
    51  
    52  func newBase(store IStore, ttl time.Duration) *base {
    53  	offset := ttl / 10
    54  	if offset > maxOffset {
    55  		offset = maxOffset
    56  	}
    57  	return &base{
    58  		store:  store,
    59  		ttl:    ttl,
    60  		offset: offset,
    61  		rand:   rand.New(rand.NewSource(uint64(time.Now().UnixNano()))),
    62  	}
    63  }