Skip to content

Commit

Permalink
add ttl
Browse files Browse the repository at this point in the history
  • Loading branch information
leeqvip committed Aug 14, 2020
1 parent 7067e98 commit fa3d498
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 4 deletions.
22 changes: 19 additions & 3 deletions cache/memory_store.go
Expand Up @@ -115,6 +115,22 @@ func (s *MemoryStore) Flush() error {
return nil
}

func (s *MemoryStore) TTL(key string) (int64, error) {
s.mu.RLock()
defer s.mu.RUnlock()

item, ok := s.items[s.prefix+key]
if !ok {
return 0, errors.New("not found")
}

if item.Expired() {
return 0, errors.New("not found")
}

return item.Expiration - time.Now().UnixNano(), nil
}

// GetPrefix Get the cache key prefix.
func (s *MemoryStore) GetPrefix() string {
return s.prefix
Expand Down Expand Up @@ -151,9 +167,9 @@ func (s *MemoryStore) DeleteExpired() {
// Find the item chronologically closest to its end-of-lifespan.
sub := item.Expiration - time.Now().UnixNano()

if smallestDuration == 0{
smallestDuration = time.Duration(sub)*time.Nanosecond
}else{
if smallestDuration == 0 {
smallestDuration = time.Duration(sub) * time.Nanosecond
} else {
if time.Duration(sub)*time.Nanosecond < smallestDuration {
smallestDuration = time.Duration(sub) * time.Nanosecond
}
Expand Down
9 changes: 8 additions & 1 deletion cache/redis_store.go
Expand Up @@ -75,7 +75,7 @@ func (s *RedisStore) Flush() error {
for {
arr, err := redis.Values(c.Do("SCAN", iter, "MATCH", s.prefix+"*"))
if err != nil {
return err
return err
}

iter, _ = redis.Int(arr[0], nil)
Expand All @@ -94,6 +94,13 @@ func (s *RedisStore) Flush() error {
return err
}

func (s *RedisStore) TTL(key string) (int64, error) {
c := s.pool.Get()
defer c.Close()

return redis.Int64(c.Do("TTL", s.prefix+key))
}

// SetPool Get the redis pool.
func (s *RedisStore) SetPool(pool *redis.Pool) *RedisStore {
s.pool = pool
Expand Down
5 changes: 5 additions & 0 deletions cache/repository.go
Expand Up @@ -88,6 +88,11 @@ func (r *Repository) Clear() error {
return r.store.Flush()
}

// TTL get the ttl of the key.
func (r *Repository) TTL(key string) (int64, error) {
return r.store.TTL(key)
}

// GetStore Get the cache store implementation.
func (r *Repository) GetStore() Store {
return r.store
Expand Down
3 changes: 3 additions & 0 deletions cache/store.go
Expand Up @@ -19,5 +19,8 @@ type Store interface {

// Flush Remove all items from the cache.
Flush() error

// TTL get the ttl of the key.
TTL(key string) (int64, error)
}

0 comments on commit fa3d498

Please sign in to comment.