缓存文件实现Sendfile

This commit is contained in:
GoEdgeLab
2022-04-04 19:45:57 +08:00
parent 2df6e5a51b
commit 149ffd400f
7 changed files with 41 additions and 2 deletions

View File

@@ -819,6 +819,14 @@ func (this *FileStorage) IgnoreKey(key string) {
this.ignoreKeys.Push(key)
}
// CanSendfile 是否支持Sendfile
func (this *FileStorage) CanSendfile() bool {
if this.options == nil {
return false
}
return this.options.EnableSendfile
}
// 绝对路径
func (this *FileStorage) dir() string {
return this.options.Dir + "/p" + strconv.FormatInt(this.policy.Id, 10) + "/"

View File

@@ -51,4 +51,7 @@ type StorageInterface interface {
// IgnoreKey 忽略某个Key即不缓存某个Key
IgnoreKey(key string)
// CanSendfile 是否支持Sendfile
CanSendfile() bool
}

View File

@@ -347,6 +347,11 @@ func (this *MemoryStorage) IgnoreKey(key string) {
this.ignoreKeys.Push(key)
}
// CanSendfile 是否支持Sendfile
func (this *MemoryStorage) CanSendfile() bool {
return false
}
// 计算Key Hash
func (this *MemoryStorage) hash(key string) uint64 {
return xxhash.Sum64String(key)

View File

@@ -540,7 +540,15 @@ func (this *HTTPRequest) doCacheRead(useStale bool) (shouldStop bool) {
this.writer.Prepare(resp, fileSize, reader.Status(), false)
this.writer.WriteHeader(reader.Status())
_, err = io.CopyBuffer(this.writer, resp.Body, buf)
if storage.CanSendfile() {
if fp, canSendFile := this.writer.canSendfile(); canSendFile {
this.writer.sentBodyBytes, err = io.CopyBuffer(this.writer.rawWriter, fp, buf)
} else {
_, err = io.CopyBuffer(this.writer, resp.Body, buf)
}
} else {
_, err = io.CopyBuffer(this.writer, resp.Body, buf)
}
if err == io.EOF {
err = nil
}

View File

@@ -1058,7 +1058,9 @@ func (this *HTTPWriter) Close() {
}
}
this.sentBodyBytes = this.counterWriter.TotalBytes()
if this.sentBodyBytes == 0 {
this.sentBodyBytes = this.counterWriter.TotalBytes()
}
}
// Hijack Hijack

View File

@@ -0,0 +1,9 @@
// Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
//go:build !plus
// +build !plus
package nodes
func (this *HTTPWriter) canSendfile() (*os.File, bool) {
return nil, false
}

View File

@@ -13,6 +13,10 @@ func NewBytesCounterWriter(rawWriter io.Writer) *BytesCounterWriter {
return &BytesCounterWriter{writer: rawWriter}
}
func (this *BytesCounterWriter) RawWriter() io.Writer {
return this.writer
}
func (this *BytesCounterWriter) Write(p []byte) (n int, err error) {
n, err = this.writer.Write(p)
this.count += int64(n)