redis/internal/pool/conn.go

82 lines
1.4 KiB
Go
Raw Normal View History

package pool
import (
"net"
"sync/atomic"
"time"
2016-07-02 15:52:10 +03:00
2017-02-18 17:42:34 +03:00
"github.com/go-redis/redis/internal/proto"
)
2016-03-12 13:41:02 +03:00
var noDeadline = time.Time{}
type Conn struct {
netConn net.Conn
Rd *proto.Reader
WB *proto.WriteBuffer
2016-03-15 15:04:35 +03:00
Inited bool
usedAt atomic.Value
}
func NewConn(netConn net.Conn) *Conn {
cn := &Conn{
netConn: netConn,
}
2018-08-06 11:54:47 +03:00
buf := proto.NewElasticBufReader(netConn)
cn.Rd = proto.NewReader(buf)
cn.WB = proto.NewWriteBuffer(buf)
cn.SetUsedAt(time.Now())
return cn
}
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)
}
func (cn *Conn) IsStale(timeout time.Duration) bool {
return timeout > 0 && time.Since(cn.UsedAt()) > timeout
2016-03-12 13:41:02 +03:00
}
2018-07-22 09:27:36 +03:00
func (cn *Conn) SetReadTimeout(timeout time.Duration) {
now := time.Now()
cn.SetUsedAt(now)
if timeout > 0 {
2018-07-22 09:27:36 +03:00
cn.netConn.SetReadDeadline(now.Add(timeout))
} else {
cn.netConn.SetReadDeadline(noDeadline)
}
}
2018-07-22 09:27:36 +03:00
func (cn *Conn) SetWriteTimeout(timeout time.Duration) {
now := time.Now()
cn.SetUsedAt(now)
if timeout > 0 {
2018-07-22 09:27:36 +03:00
cn.netConn.SetWriteDeadline(now.Add(timeout))
} else {
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()
}
2016-03-15 15:04:35 +03:00
func (cn *Conn) Close() error {
return cn.netConn.Close()
}