redis/internal/pool/conn.go

121 lines
2.2 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"
)
2018-08-15 11:53:15 +03:00
func makeBuffer() []byte {
const defaulBufSize = 4096
return make([]byte, defaulBufSize)
}
2016-03-12 13:41:02 +03:00
var noDeadline = time.Time{}
type Conn struct {
netConn net.Conn
2018-08-15 11:53:15 +03:00
buf []byte
rd proto.Reader
rdLocked bool
wb *proto.WriteBuffer
2018-08-12 10:08:21 +03:00
InitedAt time.Time
pooled bool
usedAt atomic.Value
}
func NewConn(netConn net.Conn) *Conn {
cn := &Conn{
netConn: netConn,
2018-08-15 11:53:15 +03:00
buf: makeBuffer(),
}
2018-08-15 11:53:15 +03:00
cn.rd = proto.NewReader(proto.NewElasticBufReader(netConn))
2018-08-06 13:59:15 +03:00
cn.wb = proto.NewWriteBuffer()
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
2018-08-15 11:53:15 +03:00
cn.rd.Reset(netConn)
}
2018-08-15 11:53:15 +03:00
func (cn *Conn) setReadTimeout(timeout time.Duration) error {
now := time.Now()
cn.SetUsedAt(now)
if timeout > 0 {
2018-08-15 11:53:15 +03:00
return cn.netConn.SetReadDeadline(now.Add(timeout))
}
2018-08-15 11:53:15 +03:00
return cn.netConn.SetReadDeadline(noDeadline)
}
2018-08-15 11:53:15 +03:00
func (cn *Conn) setWriteTimeout(timeout time.Duration) error {
now := time.Now()
cn.SetUsedAt(now)
if timeout > 0 {
2018-08-15 11:53:15 +03:00
return cn.netConn.SetWriteDeadline(now.Add(timeout))
}
2018-08-15 11:53:15 +03: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()
}
2018-08-15 11:53:15 +03:00
func (cn *Conn) LockReaderBuffer() {
cn.rdLocked = true
cn.rd.ResetBuffer(makeBuffer())
2018-08-06 13:59:15 +03:00
}
2018-08-15 11:53:15 +03:00
func (cn *Conn) WithReader(timeout time.Duration, fn func(rd proto.Reader) error) error {
_ = cn.setReadTimeout(timeout)
if !cn.rdLocked {
cn.rd.ResetBuffer(cn.buf)
2018-08-06 13:59:15 +03:00
}
2018-08-15 11:53:15 +03:00
err := fn(cn.rd)
if !cn.rdLocked {
cn.buf = cn.rd.Buffer()
2018-08-06 13:59:15 +03:00
}
2018-08-15 11:53:15 +03:00
2018-08-06 13:59:15 +03:00
return err
}
2018-08-15 11:53:15 +03:00
func (cn *Conn) WithWriter(timeout time.Duration, fn func(wb *proto.WriteBuffer) error) error {
_ = cn.setWriteTimeout(timeout)
cn.wb.ResetBuffer(cn.buf)
firstErr := fn(cn.wb)
_, err := cn.netConn.Write(cn.wb.Bytes())
cn.buf = cn.wb.Buffer()
if err != nil && firstErr == nil {
firstErr = err
}
return firstErr
}
2016-03-15 15:04:35 +03:00
func (cn *Conn) Close() error {
return cn.netConn.Close()
}