redis.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package redis
  2. import (
  3. "fmt"
  4. "time"
  5. "github.com/go-redis/redis"
  6. )
  7. // Config redis配置参数
  8. type Config struct {
  9. Addr string
  10. DB int
  11. Password string
  12. KeyPrefix string
  13. }
  14. // NewStore 创建基于redis存储实例
  15. func NewStore(cfg *Config) *Store {
  16. cli := redis.NewClient(&redis.Options{
  17. Addr: cfg.Addr,
  18. DB: cfg.DB,
  19. Password: cfg.Password,
  20. })
  21. return &Store{
  22. cli: cli,
  23. prefix: cfg.KeyPrefix,
  24. }
  25. }
  26. type redisClienter interface {
  27. Get(key string) *redis.StringCmd
  28. Set(key string, value interface{}, expiration time.Duration) *redis.StatusCmd
  29. Expire(key string, expiration time.Duration) *redis.BoolCmd
  30. Exists(keys ...string) *redis.IntCmd
  31. TxPipeline() redis.Pipeliner
  32. Del(keys ...string) *redis.IntCmd
  33. Close() error
  34. }
  35. // Store redis存储
  36. type Store struct {
  37. cli redisClienter
  38. prefix string
  39. }
  40. func (a *Store) wrapperKey(key string) string {
  41. return fmt.Sprintf("%s%s", "login:auth:", key)
  42. }
  43. // Get ...
  44. func (a *Store) Get(userId string) (string, error) {
  45. cmd := a.cli.Get(a.wrapperKey(userId))
  46. err := cmd.Err()
  47. if err != nil {
  48. return "", err
  49. }
  50. return cmd.Val(), nil
  51. }
  52. // Set ...
  53. func (a *Store) Set(userId string, value interface{}, expiration ...time.Duration) error {
  54. var expTime time.Duration
  55. if len(expiration) > 0 {
  56. expTime = expiration[0]
  57. }
  58. cmd := a.cli.Set(a.wrapperKey(userId), value, expTime)
  59. return cmd.Err()
  60. }
  61. // Set ...
  62. func (a *Store) Del(userId string) error {
  63. cmd := a.cli.Del(a.wrapperKey(userId))
  64. return cmd.Err()
  65. }
  66. // Check ...
  67. func (a *Store) Check(userId string) (bool, error) {
  68. cmd := a.cli.Exists(a.wrapperKey(userId))
  69. if err := cmd.Err(); err != nil {
  70. return false, err
  71. }
  72. return cmd.Val() > 0, nil
  73. }
  74. // Close ...
  75. func (a *Store) Close() error {
  76. return a.cli.Close()
  77. }