Skip to content

Commit

Permalink
feat: max idle conns
Browse files Browse the repository at this point in the history
  • Loading branch information
hiroyky committed Nov 17, 2023
1 parent 615d602 commit 37ae0da
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 11 deletions.
14 changes: 14 additions & 0 deletions memcache/conn_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,20 @@ func TestConn_isExpired(t *testing.T) {
},
}

actual := cn.isExpired(now)
if actual == true {
t.Fatalf("should be false")
}
})
t.Run("not specified", func(t *testing.T) {
now := time.Date(2023, 11, 17, 1, 0, 11, 0, time.UTC)

cn := &conn{
createdAt: time.Date(1990, 11, 17, 1, 0, 2, 0, time.UTC),
lastUsedAt: time.Date(1990, 11, 17, 1, 0, 5, 0, time.UTC),
c: &Client{},
}

actual := cn.isExpired(now)
if actual == true {
t.Fatalf("should be false")
Expand Down
19 changes: 8 additions & 11 deletions memcache/pool.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package memcache
import (
"bufio"
"net"
"sync"
"time"
)

Expand All @@ -19,7 +18,6 @@ func newPool(addr net.Addr, c *Client) *pool {
}

type pool struct {
lk sync.Mutex
addr net.Addr
freeconns chan *conn
freeconnsNum int
Expand Down Expand Up @@ -54,9 +52,6 @@ func (p *pool) enqueueNewFreeConn() error {
}

func (p *pool) getConn() (*conn, error) {
p.lk.Lock()
defer p.lk.Unlock()

if p.freeconnsNum == 0 && p.isNewConnOk() {
if err := p.enqueueNewFreeConn(); err != nil {
return nil, err
Expand Down Expand Up @@ -84,15 +79,17 @@ func (p *pool) isNewConnOk() bool {
}

func (p *pool) putFreeConn(cn *conn) {
go func() {
p.freeconnsNum++
p.freeconns <- cn
}()
if p.freeconnsNum < p.c.maxIdleConns() {
go func() {
p.freeconnsNum++
p.freeconns <- cn
}()
} else {
p.closeConn(cn)
}
}

func (p *pool) closeConn(cn *conn) {
_ = cn.nc.Close()
p.lk.Lock()
defer p.lk.Unlock()
p.openconnsNum--
}

0 comments on commit 37ae0da

Please sign in to comment.