redis_storage.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package distcache
  2. import (
  3. "time"
  4. redis "gopkg.in/redis.v2"
  5. )
  6. type redisStorage struct {
  7. c *redis.Client
  8. }
  9. func newRedisStorage(c *redis.Client) *redisStorage {
  10. opt := &redis.Options{
  11. Network: "tcp",
  12. Addr: "localhost:6379",
  13. }
  14. return &redisStorage{
  15. c: redis.NewClient(opt),
  16. }
  17. }
  18. // Set sets value to given key in session.
  19. func (s *redisStorage) Put(key string, val interface{}, expires time.Duration) error {
  20. item := &Item{Created: getTime().Unix(), Val: val}
  21. value, err := EncodeGob(item)
  22. if err != nil {
  23. return err
  24. }
  25. var status *redis.StatusCmd
  26. if expires == 0 {
  27. status = s.c.Set(key, string(value))
  28. } else {
  29. status = s.c.SetEx(key, expires, string(value))
  30. }
  31. return status.Err()
  32. }
  33. // Get gets value by given key in session.
  34. func (s *redisStorage) Get(key string) (interface{}, error) {
  35. v := s.c.Get(key)
  36. item := &Item{}
  37. err := DecodeGob([]byte(v.Val()), item)
  38. if err == nil {
  39. return item.Val, nil
  40. }
  41. if err.Error() == "EOF" {
  42. return nil, ErrCacheItemNotFound
  43. }
  44. if err != nil {
  45. return nil, err
  46. }
  47. return item.Val, nil
  48. }
  49. // Delete delete a key from session.
  50. func (s *redisStorage) Delete(key string) error {
  51. cmd := s.c.Del(key)
  52. return cmd.Err()
  53. }
  54. // RedisProvider represents a redis session provider implementation.
  55. type RedisProvider struct {
  56. c *redis.Client
  57. duration time.Duration
  58. prefix string
  59. }
  60. // Exist returns true if session with given ID exists.
  61. func (p *RedisProvider) Exist(sid string) bool {
  62. has, err := p.c.Exists(p.prefix + sid).Result()
  63. return err == nil && has
  64. }