v1.4.1 add pool get timeout

This commit is contained in:
bryanqiu 2024-05-16 17:54:09 +08:00
parent 5298a2cabf
commit 499d8b2f00

View File

@ -1,6 +1,7 @@
package cache
import (
"context"
"encoding/json"
"errors"
"fmt"
@ -15,6 +16,7 @@ import (
var (
ErrExpired = errors.New("expired")
ErrNotFound = errors.New("not found")
ErrTimeout = errors.New("not found(timeout)")
OptWithoutGetter = optWithoutGetter{} // for get only
OptWithCreateTime = optWithCreateTime{} // for set & get
OptWithRedisConn = optWithRedisConn{} // for set & get
@ -236,7 +238,14 @@ func (c *redisCacher[T]) GetFromCache(id string, options ...Option) (*T, error)
if opt.withRedisConn != nil && opt.withRedisConn.redisconn != nil {
rds = opt.withRedisConn.redisconn
} else if c.rdsPool != nil {
rds = c.rdsPool.Get()
// timeout context
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
// redis conn from pool
rds, err = c.rdsPool.GetContext(ctx)
if err != nil {
return nil, ErrTimeout
}
defer rds.Close()
} else if c.rds != nil {
rds = c.rds
@ -296,7 +305,14 @@ func (c *redisCacher[T]) SetIntoCache(id string, t *T, options ...Option) error
if opt.withRedisConn != nil && opt.withRedisConn.redisconn != nil {
rds = opt.withRedisConn.redisconn
} else if c.rdsPool != nil {
rds = c.rdsPool.Get()
// timeout context
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
// redis conn from pool
rds, err = c.rdsPool.GetContext(ctx)
if err != nil {
return errors.New("set cache failed: 'get redis conn timeout'")
}
defer rds.Close()
} else if c.rds != nil {
rds = c.rds
@ -364,7 +380,7 @@ func (c *cacher[T]) GetFromCache(id string, options ...Option) (dat *T, err erro
log.Infof("get cache(id:%s) from redisCacher success(but expired), need try next", id)
lastExpiredDat = dat
} else {
log.Infof("get cache(id:%s) from redisCacher failed, need try next", id)
log.Infof("get cache(id:%s) from redisCacher failed, need try from next cacher", id)
}
}