Skip to content

Commit

Permalink
fix
Browse files Browse the repository at this point in the history
  • Loading branch information
hiroyky committed Nov 17, 2023
1 parent b317814 commit aa339a8
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 37 deletions.
6 changes: 3 additions & 3 deletions memcache/conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,10 @@ func (cn *conn) extendDeadline() {
}

func (cn *conn) isExpired(now time.Time) bool {
if cn.createdAt.Add(cn.c.ConnMaxLifeTime).Before(now) {
if cn.c.ConnMaxLifeTime > 0 && cn.createdAt.Add(cn.c.ConnMaxLifeTime).Before(now) {
return true
}
if cn.lastUsedAt.Add(cn.c.ConnMaxIdleTime).Before(now) {
if cn.c.ConnMaxIdleTime > 0 && cn.lastUsedAt.Add(cn.c.ConnMaxIdleTime).Before(now) {
return true
}
return false
Expand All @@ -45,7 +45,7 @@ func (cn *conn) isExpired(now time.Time) bool {
// cache miss). The purpose is to not recycle TCP connections that
// are bad.
func (cn *conn) condRelease(err *error) {
if *err == nil || resumableError(*err) {
if *err == nil || resumableError(*err) || !cn.isExpired(cn.p.nowFunc()) {
cn.release()
} else {
cn.close()
Expand Down
49 changes: 15 additions & 34 deletions memcache/pool.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,29 +28,6 @@ type pool struct {
nowFunc func() time.Time
}

func (p *pool) dequeueFreeConn() (*conn, bool) {
p.lk.Lock()
defer p.lk.Unlock()
if p.freeconns == nil {
return nil, false
}
if p.freeconnsNum == 0 {
return nil, false
}
cn := <-p.freeconns
p.freeconnsNum--

now := p.nowFunc()

if cn.isExpired(now) {
p.closeConn(cn)
return p.dequeueFreeConn()
}

cn.lastUsedAt = now
return cn, true
}

func (p *pool) enqueueNewFreeConn() error {
nc, err := p.c.dial(p.addr)
if err != nil {
Expand All @@ -68,31 +45,35 @@ func (p *pool) enqueueNewFreeConn() error {
}

go func() {
p.freeconns <- newConn
p.lk.Lock()
defer p.lk.Unlock()
p.freeconnsNum++
p.openconnsNum++
p.freeconns <- newConn
}()

return nil
}

func (p *pool) getConn() (*conn, error) {
cn, ok := p.dequeueFreeConn()
if ok {
return cn, nil
}
p.lk.Lock()
defer p.lk.Unlock()

// create new connections and enqueue freeconns if available
if p.isNewConnOk() {
if p.freeconnsNum == 0 && p.isNewConnOk() {
if err := p.enqueueNewFreeConn(); err != nil {
return nil, err
}
}

// return latest freeconn or wait until to become free
cn, _ = p.dequeueFreeConn()
cn := <-p.freeconns
p.freeconnsNum--

now := p.nowFunc()

if cn.isExpired(now) {
p.closeConn(cn)
return p.getConn()
}

cn.lastUsedAt = now
return cn, nil
}

Expand Down

0 comments on commit aa339a8

Please sign in to comment.