session_pool.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package main
  2. import (
  3. "crypto/md5"
  4. "fmt"
  5. "math/rand"
  6. "time"
  7. "redisdog/model"
  8. )
  9. type Session struct {
  10. Sess string `json:"sess"`
  11. Expire int64 `json:"expire"`
  12. Account *model.AccountsRow `json:"account"`
  13. }
  14. type SessionPoll struct {
  15. poll map[string]*Session
  16. lock chan int
  17. ttl int64
  18. }
  19. func NewSessionPoll(ttl int64) *SessionPoll {
  20. p := &SessionPoll{
  21. poll: make(map[string]*Session, 1024),
  22. lock: make(chan int, 1),
  23. ttl: ttl,
  24. }
  25. go p.timer()
  26. return p
  27. }
  28. func (p *SessionPoll) timer() {
  29. for {
  30. time.Sleep(time.Minute * 1)
  31. ts := time.Now().Unix()
  32. expired := make([]string, len(p.poll))
  33. cnt := 0
  34. p.lock <- 1
  35. for id, s := range p.poll {
  36. if s.Expire <= ts {
  37. expired[cnt] = id
  38. cnt++
  39. }
  40. }
  41. for _, id := range expired {
  42. delete(p.poll, id)
  43. }
  44. <-p.lock
  45. }
  46. }
  47. func (p *SessionPoll) Get(sessid string) (*Session, bool) {
  48. p.lock <- 1
  49. s, ok := p.poll[sessid]
  50. if ok {
  51. p.poll[sessid].Expire = time.Now().Unix() + p.ttl
  52. }
  53. <-p.lock
  54. return s, ok
  55. }
  56. func (p *SessionPoll) Set(sessid string, sess *Session) {
  57. if sess.Expire == 0 {
  58. sess.Expire = time.Now().Unix() + p.ttl
  59. }
  60. p.lock <- 1
  61. p.poll[sessid] = sess
  62. <-p.lock
  63. }
  64. func (p *SessionPoll) Del(sessid string) {
  65. p.lock <- 1
  66. delete(p.poll, sessid)
  67. <-p.lock
  68. }
  69. func makeSessionId(cliAddr string) string {
  70. return fmt.Sprintf("%x", md5.Sum([]byte(fmt.Sprintf("sess|%s|%d|d", cliAddr, time.Now().Unix(), rand.Int63()))))
  71. }