项目作者: nursik

项目描述 :
Go map with TTLs.
高级语言: Go
项目地址: git://github.com/nursik/go-expire-map.git
创建时间: 2019-06-28T04:04:42Z
项目社区:https://github.com/nursik/go-expire-map

开源协议:MIT License

下载


Go expire map

GoDoc
Go Report Card

Disclaimer!!

This package is considered deprecated as there are more API rich and faster solutions like ccache or ttlcache. Also, library uses UnixNano instead of time.Time, which makes it to fail during system time (wall clock) adjustments.

Quick start

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/nursik/go-expire-map"
  5. "time"
  6. )
  7. func main() {
  8. expireMap := expiremap.New()
  9. // You must call Close(), when you do not need the map anymore
  10. defer expireMap.Close()
  11. // GMT Wednesday, 1 January 2025, 0:00:00
  12. far := time.Unix(1735689600, 0)
  13. ttl := far.Sub(time.Now())
  14. // Insert
  15. expireMap.Set(1, 1, ttl)
  16. // Get value
  17. v, ok := expireMap.Get(1)
  18. fmt.Println(v, ok)
  19. // Output 1 true
  20. // Get TTL
  21. v = expireMap.GetTTL(1)
  22. // The output is equal to ~ ttl
  23. fmt.Println(v)
  24. // Update TTL
  25. v, ok = expireMap.SetTTL(1, time.Second)
  26. fmt.Println(v, ok)
  27. // Output 1 true
  28. time.Sleep(time.Second + time.Millisecond)
  29. // Because key is already expired, it returns nil, false
  30. v, ok = expireMap.SetTTL(1, ttl)
  31. fmt.Println(v, ok)
  32. // Output nil false
  33. // Because key is already expired, it returns nil, false
  34. v, ok = expireMap.Get(1)
  35. fmt.Println(v, ok)
  36. // Output nil false
  37. }

Why/when

  • You need thread safe map with comparable keys and interface values
  • You have a lot of inserts with the same TTL. If they all expire at the same time you don’t want your app freeze
  • You need both active and passive expiration
  • You need notifications about inserts, update, deletes and expirations