Skip to content

Commit 2e1f478

Browse files
committed
Exponential backoff and dial retrying
1 parent 8d39553 commit 2e1f478

1 file changed

Lines changed: 22 additions & 1 deletion

File tree

memcache/memcache.go

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,8 @@ const (
7171
// DefaultMaxIdleConns is the default maximum number of idle connections
7272
// kept for any single address.
7373
DefaultMaxIdleConns = 2
74+
// maximum number of times to attempt to reconnect
75+
maxRetries = 10
7476
)
7577

7678
const buffered = 8 // arbitrary buffered channel size, for readability
@@ -370,7 +372,26 @@ func (c *Client) withAddrRw(addr net.Addr, fn func(*conn) error) (err error) {
370372
return err
371373
}
372374
defer cn.condRelease(&err)
373-
return fn(cn)
375+
376+
// Exponential backoff (based on Ethernet)
377+
retries := 0
378+
err = fn(cn)
379+
if err == io.EOF { // Bad connection
380+
cn.nc.Close()
381+
for err != nil && retries < maxRetries {
382+
retries++
383+
backoffCoefficient := int(math.Pow(float64(2), float64(retries))) - 1
384+
sleepFor := time.Nanosecond * time.Duration(50000*backoffCoefficient)
385+
time.Sleep(sleepFor)
386+
cn, err = c.getConn(addr)
387+
if err != nil {
388+
continue
389+
}
390+
err = fn(cn)
391+
}
392+
}
393+
394+
return
374395
}
375396

376397
func (c *Client) withKeyRw(key string, fn func(*conn) error) error {

0 commit comments

Comments
 (0)