| 1 |
package pool |
| 2 |
|
| 3 |
import ( |
| 4 |
"net" |
| 5 |
"sync/atomic" |
| 6 |
"time" |
| 7 |
|
| 8 |
"gopkg.in/redis.v5/internal/proto" |
| 9 |
) |
| 10 |
|
| 11 |
var noDeadline = time.Time{} |
| 12 |
|
| 13 |
type Conn struct { |
| 14 |
netConn net.Conn |
| 15 |
|
| 16 |
Rd *proto.Reader |
| 17 |
Wb *proto.WriteBuffer |
| 18 |
|
| 19 |
Inited bool |
| 20 |
usedAt atomic.Value |
| 21 |
} |
| 22 |
|
| 23 |
func NewConn(netConn net.Conn) *Conn { |
| 24 |
cn := &Conn{ |
| 25 |
netConn: netConn, |
| 26 |
Wb: proto.NewWriteBuffer(), |
| 27 |
} |
| 28 |
cn.Rd = proto.NewReader(cn.netConn) |
| 29 |
cn.SetUsedAt(time.Now()) |
| 30 |
return cn |
| 31 |
} |
| 32 |
|
| 33 |
func (cn *Conn) UsedAt() time.Time { |
| 34 |
return cn.usedAt.Load().(time.Time) |
| 35 |
} |
| 36 |
|
| 37 |
func (cn *Conn) SetUsedAt(tm time.Time) { |
| 38 |
cn.usedAt.Store(tm) |
| 39 |
} |
| 40 |
|
| 41 |
func (cn *Conn) SetNetConn(netConn net.Conn) { |
| 42 |
cn.netConn = netConn |
| 43 |
cn.Rd.Reset(netConn) |
| 44 |
} |
| 45 |
|
| 46 |
func (cn *Conn) IsStale(timeout time.Duration) bool { |
| 47 |
return timeout > 0 && time.Since(cn.UsedAt()) > timeout |
| 48 |
} |
| 49 |
|
| 50 |
func (cn *Conn) SetReadTimeout(timeout time.Duration) error { |
| 51 |
now := time.Now() |
| 52 |
cn.SetUsedAt(now) |
| 53 |
if timeout > 0 { |
| 54 |
return cn.netConn.SetReadDeadline(now.Add(timeout)) |
| 55 |
} |
| 56 |
return cn.netConn.SetReadDeadline(noDeadline) |
| 57 |
} |
| 58 |
|
| 59 |
func (cn *Conn) SetWriteTimeout(timeout time.Duration) error { |
| 60 |
now := time.Now() |
| 61 |
cn.SetUsedAt(now) |
| 62 |
if timeout > 0 { |
| 63 |
return cn.netConn.SetWriteDeadline(now.Add(timeout)) |
| 64 |
} |
| 65 |
return cn.netConn.SetWriteDeadline(noDeadline) |
| 66 |
} |
| 67 |
|
| 68 |
func (cn *Conn) Write(b []byte) (int, error) { |
| 69 |
return cn.netConn.Write(b) |
| 70 |
} |
| 71 |
|
| 72 |
func (cn *Conn) RemoteAddr() net.Addr { |
| 73 |
return cn.netConn.RemoteAddr() |
| 74 |
} |
| 75 |
|
| 76 |
func (cn *Conn) Close() error { |
| 77 |
return cn.netConn.Close() |
| 78 |
} |