2017-01-14 17:42:10 +00:00
|
|
|
package pool
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net"
|
2017-07-25 12:58:07 +00:00
|
|
|
"sync/atomic"
|
2017-01-14 17:42:10 +00:00
|
|
|
"time"
|
|
|
|
|
|
|
|
"gopkg.in/redis.v5/internal/proto"
|
|
|
|
)
|
|
|
|
|
|
|
|
var noDeadline = time.Time{}
|
|
|
|
|
|
|
|
type Conn struct {
|
2017-07-25 12:58:07 +00:00
|
|
|
netConn net.Conn
|
|
|
|
|
|
|
|
Rd *proto.Reader
|
|
|
|
Wb *proto.WriteBuffer
|
2017-01-14 17:42:10 +00:00
|
|
|
|
|
|
|
Inited bool
|
2017-07-25 12:58:07 +00:00
|
|
|
usedAt atomic.Value
|
2017-01-14 17:42:10 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewConn(netConn net.Conn) *Conn {
|
|
|
|
cn := &Conn{
|
2017-07-25 12:58:07 +00:00
|
|
|
netConn: netConn,
|
2017-01-14 17:42:10 +00:00
|
|
|
Wb: proto.NewWriteBuffer(),
|
|
|
|
}
|
2017-07-25 12:58:07 +00:00
|
|
|
cn.Rd = proto.NewReader(cn.netConn)
|
|
|
|
cn.SetUsedAt(time.Now())
|
2017-01-14 17:42:10 +00:00
|
|
|
return cn
|
|
|
|
}
|
|
|
|
|
2017-07-25 12:58:07 +00:00
|
|
|
func (cn *Conn) UsedAt() time.Time {
|
|
|
|
return cn.usedAt.Load().(time.Time)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (cn *Conn) SetUsedAt(tm time.Time) {
|
|
|
|
cn.usedAt.Store(tm)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (cn *Conn) SetNetConn(netConn net.Conn) {
|
|
|
|
cn.netConn = netConn
|
|
|
|
cn.Rd.Reset(netConn)
|
|
|
|
}
|
|
|
|
|
2017-01-14 17:42:10 +00:00
|
|
|
func (cn *Conn) IsStale(timeout time.Duration) bool {
|
2017-07-25 12:58:07 +00:00
|
|
|
return timeout > 0 && time.Since(cn.UsedAt()) > timeout
|
2017-01-14 17:42:10 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (cn *Conn) SetReadTimeout(timeout time.Duration) error {
|
2017-07-25 12:58:07 +00:00
|
|
|
now := time.Now()
|
|
|
|
cn.SetUsedAt(now)
|
2017-01-14 17:42:10 +00:00
|
|
|
if timeout > 0 {
|
2017-07-25 12:58:07 +00:00
|
|
|
return cn.netConn.SetReadDeadline(now.Add(timeout))
|
2017-01-14 17:42:10 +00:00
|
|
|
}
|
2017-07-25 12:58:07 +00:00
|
|
|
return cn.netConn.SetReadDeadline(noDeadline)
|
2017-01-14 17:42:10 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (cn *Conn) SetWriteTimeout(timeout time.Duration) error {
|
2017-07-25 12:58:07 +00:00
|
|
|
now := time.Now()
|
|
|
|
cn.SetUsedAt(now)
|
2017-01-14 17:42:10 +00:00
|
|
|
if timeout > 0 {
|
2017-07-25 12:58:07 +00:00
|
|
|
return cn.netConn.SetWriteDeadline(now.Add(timeout))
|
2017-01-14 17:42:10 +00:00
|
|
|
}
|
2017-07-25 12:58:07 +00:00
|
|
|
return cn.netConn.SetWriteDeadline(noDeadline)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (cn *Conn) Write(b []byte) (int, error) {
|
|
|
|
return cn.netConn.Write(b)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (cn *Conn) RemoteAddr() net.Addr {
|
|
|
|
return cn.netConn.RemoteAddr()
|
2017-01-14 17:42:10 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (cn *Conn) Close() error {
|
2017-07-25 12:58:07 +00:00
|
|
|
return cn.netConn.Close()
|
2017-01-14 17:42:10 +00:00
|
|
|
}
|