1
0
mirror of https://github.com/kataras/iris.git synced 2025-12-30 08:17:18 +00:00

redis sessiondb: support more than one driver - builtin redigo(default) and radix - rel to: #1328

Former-commit-id: 1eee58f2c49f64899fffc3ad61bcf074f8949cc1
This commit is contained in:
Gerasimos (Makis) Maropoulos
2019-08-06 18:40:13 +03:00
parent 8ac32ed27c
commit eb29a80753
7 changed files with 498 additions and 135 deletions

View File

@@ -3,27 +3,108 @@ package redis
import (
"time"
"github.com/kataras/iris/core/errors"
"github.com/kataras/iris/sessions"
"github.com/kataras/golog"
)
const (
// DefaultRedisNetwork the redis network option, "tcp".
DefaultRedisNetwork = "tcp"
// DefaultRedisAddr the redis address option, "127.0.0.1:6379".
DefaultRedisAddr = "127.0.0.1:6379"
// DefaultRedisTimeout the redis idle timeout option, time.Duration(30) * time.Second
DefaultRedisTimeout = time.Duration(30) * time.Second
// DefaultDelim ths redis delim option, "-".
DefaultDelim = "-"
)
// Config the redis configuration used inside sessions
type Config struct {
// Network protocol. Defaults to "tcp".
Network string
// Addr of the redis server. Defaults to "127.0.0.1:6379".
Addr string
// Password string .If no password then no 'AUTH'. Defaults to "".
Password string
// If Database is empty "" then no 'SELECT'. Defaults to "".
Database string
// MaxActive. Defaults to 10.
MaxActive int
// Timeout for connect, write and read, defaults to 30 seconds, 0 means no timeout.
Timeout time.Duration
// Prefix "myprefix-for-this-website". Defaults to "".
Prefix string
// Delim the delimeter for the keys on the sessiondb. Defaults to "-".
Delim string
// Driver supports `Redigo()` or `Radix()` go clients for redis.
// Configure each driver by the return value of their constructors.
//
// Defaults to `Redigo()`.
Driver Driver
}
// DefaultConfig returns the default configuration for Redis service.
func DefaultConfig() Config {
return Config{
Network: DefaultRedisNetwork,
Addr: DefaultRedisAddr,
Password: "",
Database: "",
MaxActive: 10,
Timeout: DefaultRedisTimeout,
Prefix: "",
Delim: DefaultDelim,
Driver: Redigo(),
}
}
// Database the redis back-end session database for the sessions.
type Database struct {
redis *Service
c Config
}
var _ sessions.Database = (*Database)(nil)
// New returns a new redis database.
func New(cfg ...Config) *Database {
service := newService(cfg...)
if err := service.Connect(); err != nil {
c := DefaultConfig()
if len(cfg) > 0 {
c = cfg[0]
if c.Timeout < 0 {
c.Timeout = DefaultRedisTimeout
}
if c.Network == "" {
c.Network = DefaultRedisNetwork
}
if c.Addr == "" {
c.Addr = DefaultRedisAddr
}
if c.MaxActive == 0 {
c.MaxActive = 10
}
if c.Delim == "" {
c.Delim = DefaultDelim
}
if c.Driver == nil {
c.Driver = Redigo()
}
}
if err := c.Driver.Connect(c); err != nil {
panic(err)
}
db := &Database{redis: service}
_, err := db.redis.PingPong()
db := &Database{c: c}
_, err := db.c.Driver.PingPong()
if err != nil {
golog.Debugf("error connecting to redis: %v", err)
return nil
@@ -34,17 +115,17 @@ func New(cfg ...Config) *Database {
// Config returns the configuration for the redis server bridge, you can change them.
func (db *Database) Config() *Config {
return db.redis.Config
return &db.c // 6 Aug 2019 - keep that for no breaking change.
}
// Acquire receives a session's lifetime from the database,
// if the return value is LifeTime{} then the session manager sets the life time based on the expiration duration lives in configuration.
func (db *Database) Acquire(sid string, expires time.Duration) sessions.LifeTime {
seconds, hasExpiration, found := db.redis.TTL(sid)
seconds, hasExpiration, found := db.c.Driver.TTL(sid)
if !found {
// fmt.Printf("db.Acquire expires: %s. Seconds: %v\n", expires, expires.Seconds())
// not found, create an entry with ttl and return an empty lifetime, session manager will do its job.
if err := db.redis.Set(sid, sid, int64(expires.Seconds())); err != nil {
if err := db.c.Driver.Set(sid, sid, int64(expires.Seconds())); err != nil {
golog.Debug(err)
}
@@ -62,11 +143,11 @@ func (db *Database) Acquire(sid string, expires time.Duration) sessions.LifeTime
// OnUpdateExpiration will re-set the database's session's entry ttl.
// https://redis.io/commands/expire#refreshing-expires
func (db *Database) OnUpdateExpiration(sid string, newExpires time.Duration) error {
return db.redis.UpdateTTLMany(sid, int64(newExpires.Seconds()))
return db.c.Driver.UpdateTTLMany(sid, int64(newExpires.Seconds()))
}
func (db *Database) makeKey(sid, key string) string {
return sid + db.redis.Config.Delim + key
return sid + db.c.Delim + key
}
// Set sets a key value of a specific session.
@@ -80,7 +161,7 @@ func (db *Database) Set(sid string, lifetime sessions.LifeTime, key string, valu
// fmt.Println("database.Set")
// fmt.Printf("lifetime.DurationUntilExpiration(): %s. Seconds: %v\n", lifetime.DurationUntilExpiration(), lifetime.DurationUntilExpiration().Seconds())
if err = db.redis.Set(db.makeKey(sid, key), valueBytes, int64(lifetime.DurationUntilExpiration().Seconds())); err != nil {
if err = db.c.Driver.Set(db.makeKey(sid, key), valueBytes, int64(lifetime.DurationUntilExpiration().Seconds())); err != nil {
golog.Debug(err)
}
}
@@ -92,7 +173,7 @@ func (db *Database) Get(sid string, key string) (value interface{}) {
}
func (db *Database) get(key string, outPtr interface{}) {
data, err := db.redis.Get(key)
data, err := db.c.Driver.Get(key)
if err != nil {
// not found.
return
@@ -104,7 +185,7 @@ func (db *Database) get(key string, outPtr interface{}) {
}
func (db *Database) keys(sid string) []string {
keys, err := db.redis.GetKeys(sid)
keys, err := db.c.Driver.GetKeys(sid)
if err != nil {
golog.Debugf("unable to get all redis keys of session '%s': %v", sid, err)
return nil
@@ -130,7 +211,7 @@ func (db *Database) Len(sid string) (n int) {
// Delete removes a session key value based on its key.
func (db *Database) Delete(sid string, key string) (deleted bool) {
err := db.redis.Delete(db.makeKey(sid, key))
err := db.c.Driver.Delete(db.makeKey(sid, key))
if err != nil {
golog.Error(err)
}
@@ -141,7 +222,7 @@ func (db *Database) Delete(sid string, key string) (deleted bool) {
func (db *Database) Clear(sid string) {
keys := db.keys(sid)
for _, key := range keys {
if err := db.redis.Delete(key); err != nil {
if err := db.c.Driver.Delete(key); err != nil {
golog.Debugf("unable to delete session '%s' value of key: '%s': %v", sid, key, err)
}
}
@@ -153,7 +234,7 @@ func (db *Database) Release(sid string) {
// clear all $sid-$key.
db.Clear(sid)
// and remove the $sid.
db.redis.Delete(sid)
db.c.Driver.Delete(sid)
}
// Close terminates the redis connection.
@@ -162,5 +243,12 @@ func (db *Database) Close() error {
}
func closeDB(db *Database) error {
return db.redis.CloseConnection()
return db.c.Driver.CloseConnection()
}
var (
// ErrRedisClosed an error with message 'Redis is already closed'
ErrRedisClosed = errors.New("Redis is already closed")
// ErrKeyNotFound an error with message 'Key $thekey doesn't found'
ErrKeyNotFound = errors.New("Key '%s' doesn't found")
)