1 回答
TA贡献1780条经验 获得超4个赞
问题似乎是反复调用gzip.NewWriter()infunc(*CursorReader) Read([]byte) (int, error)
您正在gzip.Writer为每个调用分配一个新的Read. gzip压缩是有状态的,因此您只能Writer对所有操作使用单个实例。
解决方案#1
解决您的问题的一个相当简单的方法是读取游标中的所有行并将其传递gzip.Writer并将 gzip 压缩的内容存储到内存缓冲区中。
var cursor, _ = collection.Find(context.TODO(), filter)
defer cursor.Close(context.TODO())
// prepare a buffer to hold gzipped data
var buffer bytes.Buffer
var gz = gzip.NewWriter(&buffer)
defer gz.Close()
for cursor.Next(context.TODO()) {
if _, err = io.WriteString(gz, cursor.Current.String()); err != nil {
// handle error somehow ¯\_(ツ)_/¯
}
}
// you can now use buffer as io.Reader
// and it'll contain gzipped data for your serialized rows
_, err = s3.Upload(&s3.UploadInput{
Bucket: aws.String("..."),
Key: aws.String("...")),
Body: &buffer,
})
解决方案#2
另一种解决方案是使用goroutines创建一个流,按需读取和压缩数据,而不是在内存缓冲区中io.Pipe()。如果您正在读取的数据非常大并且您无法将所有数据都保存在内存中,这将非常有用。
var cursor, _ = collection.Find(context.TODO(), filter)
defer cursor.Close(context.TODO())
// create pipe endpoints
reader, writer := io.Pipe()
// note: io.Pipe() returns a synchronous in-memory pipe
// reads and writes block on one another
// make sure to go through docs once.
// now, since reads and writes on a pipe blocks
// we must move to a background goroutine else
// all our writes would block forever
go func() {
// order of defer here is important
// see: https://stackoverflow.com/a/24720120/6611700
// make sure gzip stream is closed before the pipe
// to ensure data is flushed properly
defer writer.Close()
var gz = gzip.NewWriter(writer)
defer gz.Close()
for cursor.Next(context.Background()) {
if _, err = io.WriteString(gz, cursor.Current.String()); err != nil {
// handle error somehow ¯\_(ツ)_/¯
}
}
}()
// you can now use reader as io.Reader
// and it'll contain gzipped data for your serialized rows
_, err = s3.Upload(&s3.UploadInput{
Bucket: aws.String("..."),
Key: aws.String("...")),
Body: reader,
})
- 1 回答
- 0 关注
- 202 浏览
添加回答
举报
