本站源代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

240 lines
5.5KB

  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. "gitea.com/macaron/session"
  22. "github.com/go-redis/redis"
  23. "github.com/unknwon/com"
  24. "gopkg.in/ini.v1"
  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.Set(s.prefix+s.sid, string(data), s.duration).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).MustInt()
  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, "", p.duration).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. v, err := p.c.Exists(p.prefix + sid).Result()
  159. return err == nil && v == 1
  160. }
  161. // Destroy deletes a session by session ID.
  162. func (p *RedisProvider) Destroy(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.Set(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. }
上海开阖软件有限公司 沪ICP备12045867号-1