redis.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. // Copyright 2013 Beego Authors
  2. // Copyright 2014 The Macaron Authors
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License"): you may
  5. // not use this file except in compliance with the License. You may obtain
  6. // a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. // License for the specific language governing permissions and limitations
  14. // under the License.
  15. package session
  16. import (
  17. "fmt"
  18. "strings"
  19. "sync"
  20. "time"
  21. "github.com/Unknwon/com"
  22. "gopkg.in/ini.v1"
  23. "gopkg.in/redis.v2"
  24. "github.com/go-macaron/session"
  25. )
  26. // RedisStore represents a redis session store implementation.
  27. type RedisStore struct {
  28. c *redis.Client
  29. prefix, sid string
  30. duration time.Duration
  31. lock sync.RWMutex
  32. data map[interface{}]interface{}
  33. }
  34. // NewRedisStore creates and returns a redis session store.
  35. func NewRedisStore(c *redis.Client, prefix, sid string, dur time.Duration, kv map[interface{}]interface{}) *RedisStore {
  36. return &RedisStore{
  37. c: c,
  38. prefix: prefix,
  39. sid: sid,
  40. duration: dur,
  41. data: kv,
  42. }
  43. }
  44. // Set sets value to given key in session.
  45. func (s *RedisStore) Set(key, val interface{}) error {
  46. s.lock.Lock()
  47. defer s.lock.Unlock()
  48. s.data[key] = val
  49. return nil
  50. }
  51. // Get gets value by given key in session.
  52. func (s *RedisStore) Get(key interface{}) interface{} {
  53. s.lock.RLock()
  54. defer s.lock.RUnlock()
  55. return s.data[key]
  56. }
  57. // Delete delete a key from session.
  58. func (s *RedisStore) Delete(key interface{}) error {
  59. s.lock.Lock()
  60. defer s.lock.Unlock()
  61. delete(s.data, key)
  62. return nil
  63. }
  64. // ID returns current session ID.
  65. func (s *RedisStore) ID() string {
  66. return s.sid
  67. }
  68. // Release releases resource and save data to provider.
  69. func (s *RedisStore) Release() error {
  70. data, err := session.EncodeGob(s.data)
  71. if err != nil {
  72. return err
  73. }
  74. return s.c.SetEx(s.prefix+s.sid, s.duration, string(data)).Err()
  75. }
  76. // Flush deletes all session data.
  77. func (s *RedisStore) Flush() error {
  78. s.lock.Lock()
  79. defer s.lock.Unlock()
  80. s.data = make(map[interface{}]interface{})
  81. return nil
  82. }
  83. // RedisProvider represents a redis session provider implementation.
  84. type RedisProvider struct {
  85. c *redis.Client
  86. duration time.Duration
  87. prefix string
  88. }
  89. // Init initializes redis session provider.
  90. // configs: network=tcp,addr=:6379,password=macaron,db=0,pool_size=100,idle_timeout=180,prefix=session;
  91. func (p *RedisProvider) Init(maxlifetime int64, configs string) (err error) {
  92. p.duration, err = time.ParseDuration(fmt.Sprintf("%ds", maxlifetime))
  93. if err != nil {
  94. return err
  95. }
  96. cfg, err := ini.Load([]byte(strings.Replace(configs, ",", "\n", -1)))
  97. if err != nil {
  98. return err
  99. }
  100. opt := &redis.Options{
  101. Network: "tcp",
  102. }
  103. for k, v := range cfg.Section("").KeysHash() {
  104. switch k {
  105. case "network":
  106. opt.Network = v
  107. case "addr":
  108. opt.Addr = v
  109. case "password":
  110. opt.Password = v
  111. case "db":
  112. opt.DB = com.StrTo(v).MustInt64()
  113. case "pool_size":
  114. opt.PoolSize = com.StrTo(v).MustInt()
  115. case "idle_timeout":
  116. opt.IdleTimeout, err = time.ParseDuration(v + "s")
  117. if err != nil {
  118. return fmt.Errorf("error parsing idle timeout: %v", err)
  119. }
  120. case "prefix":
  121. p.prefix = v
  122. default:
  123. return fmt.Errorf("session/redis: unsupported option '%s'", k)
  124. }
  125. }
  126. p.c = redis.NewClient(opt)
  127. return p.c.Ping().Err()
  128. }
  129. // Read returns raw session store by session ID.
  130. func (p *RedisProvider) Read(sid string) (session.RawStore, error) {
  131. psid := p.prefix + sid
  132. if !p.Exist(sid) {
  133. if err := p.c.Set(psid, "").Err(); err != nil {
  134. return nil, err
  135. }
  136. }
  137. var kv map[interface{}]interface{}
  138. kvs, err := p.c.Get(psid).Result()
  139. if err != nil {
  140. return nil, err
  141. }
  142. if len(kvs) == 0 {
  143. kv = make(map[interface{}]interface{})
  144. } else {
  145. kv, err = session.DecodeGob([]byte(kvs))
  146. if err != nil {
  147. return nil, err
  148. }
  149. }
  150. return NewRedisStore(p.c, p.prefix, sid, p.duration, kv), nil
  151. }
  152. // Exist returns true if session with given ID exists.
  153. func (p *RedisProvider) Exist(sid string) bool {
  154. has, err := p.c.Exists(p.prefix + sid).Result()
  155. return err == nil && has
  156. }
  157. // Destory deletes a session by session ID.
  158. func (p *RedisProvider) Destory(sid string) error {
  159. return p.c.Del(p.prefix + sid).Err()
  160. }
  161. // Regenerate regenerates a session store from old session ID to new one.
  162. func (p *RedisProvider) Regenerate(oldsid, sid string) (_ session.RawStore, err error) {
  163. poldsid := p.prefix + oldsid
  164. psid := p.prefix + sid
  165. if p.Exist(sid) {
  166. return nil, fmt.Errorf("new sid '%s' already exists", sid)
  167. } else if !p.Exist(oldsid) {
  168. // Make a fake old session.
  169. if err = p.c.SetEx(poldsid, p.duration, "").Err(); err != nil {
  170. return nil, err
  171. }
  172. }
  173. if err = p.c.Rename(poldsid, psid).Err(); err != nil {
  174. return nil, err
  175. }
  176. var kv map[interface{}]interface{}
  177. kvs, err := p.c.Get(psid).Result()
  178. if err != nil {
  179. return nil, err
  180. }
  181. if len(kvs) == 0 {
  182. kv = make(map[interface{}]interface{})
  183. } else {
  184. kv, err = session.DecodeGob([]byte(kvs))
  185. if err != nil {
  186. return nil, err
  187. }
  188. }
  189. return NewRedisStore(p.c, p.prefix, sid, p.duration, kv), nil
  190. }
  191. // Count counts and returns number of sessions.
  192. func (p *RedisProvider) Count() int {
  193. return int(p.c.DbSize().Val())
  194. }
  195. // GC calls GC to clean expired sessions.
  196. func (_ *RedisProvider) GC() {}
  197. func init() {
  198. session.Register("redis", &RedisProvider{})
  199. }