From 499d8b2f00e2b12ae1ba9066b4f9304c15d28c1c Mon Sep 17 00:00:00 2001 From: bryanqiu Date: Thu, 16 May 2024 17:54:09 +0800 Subject: [PATCH] v1.4.1 add pool get timeout --- cache.go | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/cache.go b/cache.go index 9f4e0ba..e48d20d 100644 --- a/cache.go +++ b/cache.go @@ -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) } }