cache.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package cache
  2. import (
  3. "errors"
  4. "fmt"
  5. "strconv"
  6. "strings"
  7. "github.com/shomali11/xredis"
  8. )
  9. type BotCache interface {
  10. Store(key, data string, ttl int) (err error)
  11. Retrieve(key string, remove bool) (value string, found bool, err error)
  12. Remove(key string) (err error)
  13. }
  14. type RedisCache struct {
  15. cacheManager *xredis.Client
  16. defaultTTL int
  17. databaseId int
  18. }
  19. func NewRedisCache(redisCondig string) RedisCache {
  20. // Need to split based on :
  21. hostParts := strings.Split(redisCondig, ":")
  22. port := 6379
  23. if len(hostParts) > 1 {
  24. // port is second param
  25. var err error
  26. if port, err = strconv.Atoi(hostParts[1]); err != nil {
  27. fmt.Println("Defaulting to redis port ", port)
  28. }
  29. }
  30. databaseId := 1 // default other than 0
  31. if len(hostParts) > 2 {
  32. // redis db id is third param
  33. var err error
  34. if databaseId, err = strconv.Atoi(hostParts[2]); err != nil {
  35. fmt.Println("Something wrong with redis dbId .. Defaulting to redis db ", databaseId)
  36. }
  37. }
  38. options := &xredis.Options{
  39. Host: hostParts[0],
  40. Port: port,
  41. Database: databaseId,
  42. }
  43. // Default to an hour
  44. defaultTTL := 3600
  45. c := RedisCache{xredis.SetupClient(options), defaultTTL, databaseId}
  46. // defer c.cacheManager.Close()
  47. return c
  48. }
  49. /**
  50. We always assume data is a strings*/
  51. func (c RedisCache) Store(key, value string, ttl int) (err error) {
  52. _, err = c.cacheManager.Set(key, value)
  53. if err != nil {
  54. return err
  55. }
  56. // Set TTL - default an hour
  57. _, err = c.cacheManager.Expire(key, int64(ttl))
  58. return err
  59. }
  60. func (c RedisCache) Retrieve(key string, delete bool) (value string, found bool, err error) {
  61. found = false
  62. value, got, reterr := c.cacheManager.Get(key)
  63. if !got || reterr != nil {
  64. err = errors.New("Cache Key Not Found")
  65. return
  66. }
  67. found = true
  68. if delete {
  69. c.Remove(key)
  70. }
  71. return
  72. }
  73. func (c RedisCache) Remove(key string) error {
  74. _, err := c.cacheManager.Del(key)
  75. return err
  76. }