2016-03-12 11:52:13 +03:00
|
|
|
package pool
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net"
|
|
|
|
"time"
|
2016-07-02 15:52:10 +03:00
|
|
|
|
2016-10-09 13:49:28 +03:00
|
|
|
"gopkg.in/redis.v5/internal/proto"
|
2016-03-12 11:52:13 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
const defaultBufSize = 4096
|
|
|
|
|
2016-03-12 13:41:02 +03:00
|
|
|
var noDeadline = time.Time{}
|
2016-03-12 11:52:13 +03:00
|
|
|
|
|
|
|
type Conn struct {
|
2016-03-14 14:17:33 +03:00
|
|
|
NetConn net.Conn
|
2016-07-02 15:52:10 +03:00
|
|
|
Rd *proto.Reader
|
|
|
|
Wb *proto.WriteBuffer
|
2016-03-12 11:52:13 +03:00
|
|
|
|
2016-03-15 15:04:35 +03:00
|
|
|
Inited bool
|
|
|
|
UsedAt time.Time
|
|
|
|
|
2016-03-12 11:52:13 +03:00
|
|
|
ReadTimeout time.Duration
|
|
|
|
WriteTimeout time.Duration
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewConn(netConn net.Conn) *Conn {
|
|
|
|
cn := &Conn{
|
2016-03-14 14:17:33 +03:00
|
|
|
NetConn: netConn,
|
2016-07-02 15:52:10 +03:00
|
|
|
Wb: proto.NewWriteBuffer(),
|
2016-03-12 11:52:13 +03:00
|
|
|
|
|
|
|
UsedAt: time.Now(),
|
|
|
|
}
|
2016-07-02 15:52:10 +03:00
|
|
|
cn.Rd = proto.NewReader(cn)
|
2016-03-12 11:52:13 +03:00
|
|
|
return cn
|
|
|
|
}
|
|
|
|
|
2016-03-14 14:17:33 +03:00
|
|
|
func (cn *Conn) IsStale(timeout time.Duration) bool {
|
|
|
|
return timeout > 0 && time.Since(cn.UsedAt) > timeout
|
2016-03-12 13:41:02 +03:00
|
|
|
}
|
|
|
|
|
2016-03-12 11:52:13 +03:00
|
|
|
func (cn *Conn) Read(b []byte) (int, error) {
|
|
|
|
cn.UsedAt = time.Now()
|
|
|
|
if cn.ReadTimeout != 0 {
|
2016-03-14 14:17:33 +03:00
|
|
|
cn.NetConn.SetReadDeadline(cn.UsedAt.Add(cn.ReadTimeout))
|
2016-03-12 11:52:13 +03:00
|
|
|
} else {
|
2016-03-14 14:17:33 +03:00
|
|
|
cn.NetConn.SetReadDeadline(noDeadline)
|
2016-03-12 11:52:13 +03:00
|
|
|
}
|
2016-03-14 14:17:33 +03:00
|
|
|
return cn.NetConn.Read(b)
|
2016-03-12 11:52:13 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func (cn *Conn) Write(b []byte) (int, error) {
|
|
|
|
cn.UsedAt = time.Now()
|
|
|
|
if cn.WriteTimeout != 0 {
|
2016-03-14 14:17:33 +03:00
|
|
|
cn.NetConn.SetWriteDeadline(cn.UsedAt.Add(cn.WriteTimeout))
|
2016-03-12 11:52:13 +03:00
|
|
|
} else {
|
2016-03-14 14:17:33 +03:00
|
|
|
cn.NetConn.SetWriteDeadline(noDeadline)
|
2016-03-12 11:52:13 +03:00
|
|
|
}
|
2016-03-14 14:17:33 +03:00
|
|
|
return cn.NetConn.Write(b)
|
2016-03-12 11:52:13 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func (cn *Conn) RemoteAddr() net.Addr {
|
2016-03-14 14:17:33 +03:00
|
|
|
return cn.NetConn.RemoteAddr()
|
2016-03-12 11:52:13 +03:00
|
|
|
}
|
|
|
|
|
2016-03-15 15:04:35 +03:00
|
|
|
func (cn *Conn) Close() error {
|
|
|
|
return cn.NetConn.Close()
|
2016-03-12 11:52:13 +03:00
|
|
|
}
|