Skip to content

Commit b6a713c

Browse files
author
xiaobiao
committed
读取网络包内存优化
1 parent 036c016 commit b6a713c

File tree

2 files changed

+28
-6
lines changed

2 files changed

+28
-6
lines changed

packet/conn.go

+20-6
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,14 @@ package packet
33
import (
44
"bufio"
55
"bytes"
6-
"io"
7-
"net"
8-
"sync"
9-
106
"crypto/rand"
117
"crypto/rsa"
128
"crypto/sha1"
139
"crypto/x509"
1410
"encoding/pem"
11+
"io"
12+
"net"
13+
"sync"
1514

1615
. "github.com/go-mysql-org/go-mysql/mysql"
1716
"github.com/go-mysql-org/go-mysql/utils"
@@ -97,10 +96,25 @@ func (c *Conn) ReadPacketReuseMem(dst []byte) ([]byte, error) {
9796

9897
if err := c.ReadPacketTo(buf); err != nil {
9998
return nil, errors.Trace(err)
99+
}
100+
101+
readBytes := buf.Bytes()
102+
readSize := len(readBytes) + len(dst)
103+
result := make([]byte, 0, readSize)
104+
if len(dst) > 0 {
105+
result = append(result, dst...)
106+
result = append(result, readBytes...)
107+
100108
} else {
101-
result := append(dst, buf.Bytes()...)
102-
return result, nil
109+
if readSize <= utils.TooBigBlockSize {
110+
result = append(result, readBytes...)
111+
} else {
112+
// if read block is big, use read block as result and do not cache buf any more
113+
result = readBytes
114+
buf = nil
115+
}
103116
}
117+
return result, nil
104118
}
105119

106120
func (c *Conn) copyN(dst io.Writer, src io.Reader, n int64) (written int64, err error) {

utils/bytes_buffer_pool.go

+8
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,10 @@ import (
55
"sync"
66
)
77

8+
const (
9+
TooBigBlockSize = 1024 * 1024 * 4
10+
)
11+
812
var (
913
bytesBufferPool = sync.Pool{
1014
New: func() interface{} {
@@ -27,6 +31,10 @@ func BytesBufferGet() (data *bytes.Buffer) {
2731
}
2832

2933
func BytesBufferPut(data *bytes.Buffer) {
34+
if data == nil || len(data.Bytes()) > TooBigBlockSize {
35+
return
36+
}
37+
3038
select {
3139
case bytesBufferChan <- data:
3240
default:

0 commit comments

Comments
 (0)