redis.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  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. // Skip encoding if the data is empty
  71. if len(s.data) == 0 {
  72. return nil
  73. }
  74. data, err := session.EncodeGob(s.data)
  75. if err != nil {
  76. return err
  77. }
  78. return s.c.SetEx(s.prefix+s.sid, s.duration, string(data)).Err()
  79. }
  80. // Flush deletes all session data.
  81. func (s *RedisStore) Flush() error {
  82. s.lock.Lock()
  83. defer s.lock.Unlock()
  84. s.data = make(map[interface{}]interface{})
  85. return nil
  86. }
  87. // RedisProvider represents a redis session provider implementation.
  88. type RedisProvider struct {
  89. c *redis.Client
  90. duration time.Duration
  91. prefix string
  92. }
  93. // Init initializes redis session provider.
  94. // configs: network=tcp,addr=:6379,password=macaron,db=0,pool_size=100,idle_timeout=180,prefix=session;
  95. func (p *RedisProvider) Init(maxlifetime int64, configs string) (err error) {
  96. p.duration, err = time.ParseDuration(fmt.Sprintf("%ds", maxlifetime))
  97. if err != nil {
  98. return err
  99. }
  100. cfg, err := ini.Load([]byte(strings.Replace(configs, ",", "\n", -1)))
  101. if err != nil {
  102. return err
  103. }
  104. opt := &redis.Options{
  105. Network: "tcp",
  106. }
  107. for k, v := range cfg.Section("").KeysHash() {
  108. switch k {
  109. case "network":
  110. opt.Network = v
  111. case "addr":
  112. opt.Addr = v
  113. case "password":
  114. opt.Password = v
  115. case "db":
  116. opt.DB = com.StrTo(v).MustInt64()
  117. case "pool_size":
  118. opt.PoolSize = com.StrTo(v).MustInt()
  119. case "idle_timeout":
  120. opt.IdleTimeout, err = time.ParseDuration(v + "s")
  121. if err != nil {
  122. return fmt.Errorf("error parsing idle timeout: %v", err)
  123. }
  124. case "prefix":
  125. p.prefix = v
  126. default:
  127. return fmt.Errorf("session/redis: unsupported option '%s'", k)
  128. }
  129. }
  130. p.c = redis.NewClient(opt)
  131. return p.c.Ping().Err()
  132. }
  133. // Read returns raw session store by session ID.
  134. func (p *RedisProvider) Read(sid string) (session.RawStore, error) {
  135. psid := p.prefix + sid
  136. if !p.Exist(sid) {
  137. if err := p.c.Set(psid, "").Err(); err != nil {
  138. return nil, err
  139. }
  140. }
  141. var kv map[interface{}]interface{}
  142. kvs, err := p.c.Get(psid).Result()
  143. if err != nil {
  144. return nil, err
  145. }
  146. if len(kvs) == 0 {
  147. kv = make(map[interface{}]interface{})
  148. } else {
  149. kv, err = session.DecodeGob([]byte(kvs))
  150. if err != nil {
  151. return nil, err
  152. }
  153. }
  154. return NewRedisStore(p.c, p.prefix, sid, p.duration, kv), nil
  155. }
  156. // Exist returns true if session with given ID exists.
  157. func (p *RedisProvider) Exist(sid string) bool {
  158. has, err := p.c.Exists(p.prefix + sid).Result()
  159. return err == nil && has
  160. }
  161. // Destory deletes a session by session ID.
  162. func (p *RedisProvider) Destory(sid string) error {
  163. return p.c.Del(p.prefix + sid).Err()
  164. }
  165. // Regenerate regenerates a session store from old session ID to new one.
  166. func (p *RedisProvider) Regenerate(oldsid, sid string) (_ session.RawStore, err error) {
  167. poldsid := p.prefix + oldsid
  168. psid := p.prefix + sid
  169. if p.Exist(sid) {
  170. return nil, fmt.Errorf("new sid '%s' already exists", sid)
  171. } else if !p.Exist(oldsid) {
  172. // Make a fake old session.
  173. if err = p.c.SetEx(poldsid, p.duration, "").Err(); err != nil {
  174. return nil, err
  175. }
  176. }
  177. if err = p.c.Rename(poldsid, psid).Err(); err != nil {
  178. return nil, err
  179. }
  180. var kv map[interface{}]interface{}
  181. kvs, err := p.c.Get(psid).Result()
  182. if err != nil {
  183. return nil, err
  184. }
  185. if len(kvs) == 0 {
  186. kv = make(map[interface{}]interface{})
  187. } else {
  188. kv, err = session.DecodeGob([]byte(kvs))
  189. if err != nil {
  190. return nil, err
  191. }
  192. }
  193. return NewRedisStore(p.c, p.prefix, sid, p.duration, kv), nil
  194. }
  195. // Count counts and returns number of sessions.
  196. func (p *RedisProvider) Count() int {
  197. return int(p.c.DbSize().Val())
  198. }
  199. // GC calls GC to clean expired sessions.
  200. func (_ *RedisProvider) GC() {}
  201. func init() {
  202. session.Register("redis", &RedisProvider{})
  203. }