修复并发请求时内存缓存可能存在的问题

This commit is contained in:
GoEdgeLab
2021-03-03 09:38:27 +08:00
parent 5f6b270af3
commit d52199254a

View File

@@ -6,14 +6,13 @@ import (
) )
type MemoryWriter struct { type MemoryWriter struct {
key string key string
expiredAt int64 expiredAt int64
m map[uint64]*MemoryItem m map[uint64]*MemoryItem
locker *sync.RWMutex locker *sync.RWMutex
isFirstWriting bool headerSize int64
headerSize int64 bodySize int64
bodySize int64 status int
status int
hash uint64 hash uint64
item *MemoryItem item *MemoryItem
@@ -21,12 +20,15 @@ type MemoryWriter struct {
func NewMemoryWriter(m map[uint64]*MemoryItem, key string, expiredAt int64, status int, locker *sync.RWMutex) *MemoryWriter { func NewMemoryWriter(m map[uint64]*MemoryItem, key string, expiredAt int64, status int, locker *sync.RWMutex) *MemoryWriter {
w := &MemoryWriter{ w := &MemoryWriter{
m: m, m: m,
key: key, key: key,
expiredAt: expiredAt, expiredAt: expiredAt,
locker: locker, locker: locker,
isFirstWriting: true, item: &MemoryItem{
status: status, ExpiredAt: expiredAt,
Status: status,
},
status: status,
} }
w.hash = w.calculateHash(key) w.hash = w.calculateHash(key)
@@ -38,25 +40,7 @@ func (this *MemoryWriter) WriteHeader(data []byte) (n int, err error) {
this.headerSize += int64(len(data)) this.headerSize += int64(len(data))
this.locker.Lock() this.locker.Lock()
item, ok := this.m[this.hash] this.item.HeaderValue = append(this.item.HeaderValue, data...)
if ok {
item.IsDone = false
// 第一次写先清空
if this.isFirstWriting {
item.HeaderValue = nil
item.BodyValue = nil
this.isFirstWriting = false
}
item.HeaderValue = append(item.HeaderValue, data...)
} else {
item = &MemoryItem{}
item.HeaderValue = append([]byte{}, data...)
item.ExpiredAt = this.expiredAt
item.Status = this.status
this.isFirstWriting = false
}
this.item = item
this.locker.Unlock() this.locker.Unlock()
return len(data), nil return len(data), nil
} }
@@ -66,25 +50,7 @@ func (this *MemoryWriter) Write(data []byte) (n int, err error) {
this.bodySize += int64(len(data)) this.bodySize += int64(len(data))
this.locker.Lock() this.locker.Lock()
item, ok := this.m[this.hash] this.item.BodyValue = append(this.item.BodyValue, data...)
if ok {
item.IsDone = false
// 第一次写先清空
if this.isFirstWriting {
item.HeaderValue = nil
item.BodyValue = nil
this.isFirstWriting = false
}
item.BodyValue = append(item.BodyValue, data...)
} else {
item = &MemoryItem{}
item.BodyValue = append([]byte{}, data...)
item.ExpiredAt = this.expiredAt
item.Status = this.status
this.isFirstWriting = false
}
this.item = item
this.locker.Unlock() this.locker.Unlock()
return len(data), nil return len(data), nil
} }