123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- package cache
- import (
- "errors"
- "fmt"
- "strconv"
- "strings"
- "github.com/shomali11/xredis"
- )
- type BotCache interface {
- Store(key, data string, ttl int) (err error)
- Retrieve(key string, remove bool) (value string, found bool, err error)
- Remove(key string) (err error)
- }
- type RedisCache struct {
- cacheManager *xredis.Client
- defaultTTL int
- databaseId int
- }
- func NewRedisCache(redisCondig string) RedisCache {
- // Need to split based on :
- hostParts := strings.Split(redisCondig, ":")
- port := 6379
- if len(hostParts) > 1 {
- // port is second param
- var err error
- if port, err = strconv.Atoi(hostParts[1]); err != nil {
- fmt.Println("Defaulting to redis port ", port)
- }
- }
- databaseId := 1 // default other than 0
- if len(hostParts) > 2 {
- // redis db id is third param
- var err error
- if databaseId, err = strconv.Atoi(hostParts[2]); err != nil {
- fmt.Println("Something wrong with redis dbId .. Defaulting to redis db ", databaseId)
- }
- }
- options := &xredis.Options{
- Host: hostParts[0],
- Port: port,
- Database: databaseId,
- }
- // Default to an hour
- defaultTTL := 3600
- c := RedisCache{xredis.SetupClient(options), defaultTTL, databaseId}
- // defer c.cacheManager.Close()
- return c
- }
- /**
- We always assume data is a strings*/
- func (c RedisCache) Store(key, value string, ttl int) (err error) {
- _, err = c.cacheManager.Set(key, value)
- if err != nil {
- return err
- }
- // Set TTL - default an hour
- _, err = c.cacheManager.Expire(key, int64(ttl))
- return err
- }
- func (c RedisCache) Retrieve(key string, delete bool) (value string, found bool, err error) {
- found = false
- value, got, reterr := c.cacheManager.Get(key)
- if !got || reterr != nil {
- err = errors.New("Cache Key Not Found")
- return
- }
- found = true
- if delete {
- c.Remove(key)
- }
- return
- }
- func (c RedisCache) Remove(key string) error {
- _, err := c.cacheManager.Del(key)
- return err
- }
|