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

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

View File

@@ -10,7 +10,6 @@ type MemoryWriter struct {
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
@@ -25,7 +24,10 @@ func NewMemoryWriter(m map[uint64]*MemoryItem, key string, expiredAt int64, stat
key: key, key: key,
expiredAt: expiredAt, expiredAt: expiredAt,
locker: locker, locker: locker,
isFirstWriting: true, item: &MemoryItem{
ExpiredAt: expiredAt,
Status: status,
},
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
} }