diff --git a/internal/caches/storage_memory.go b/internal/caches/storage_memory.go index 039db45..0bcadf9 100644 --- a/internal/caches/storage_memory.go +++ b/internal/caches/storage_memory.go @@ -77,10 +77,9 @@ func (this *MemoryStorage) OpenReader(key string) (Reader, error) { hash := this.hash(key) this.locker.RLock() - defer this.locker.RUnlock() - item := this.valuesMap[hash] if item == nil || !item.IsDone { + this.locker.RUnlock() return nil, ErrNotFound } @@ -88,10 +87,13 @@ func (this *MemoryStorage) OpenReader(key string) (Reader, error) { reader := NewMemoryReader(item) err := reader.Init() if err != nil { + this.locker.RUnlock() return nil, err } + this.locker.RUnlock() return reader, nil } + this.locker.RUnlock() _ = this.Delete(key) @@ -137,7 +139,7 @@ func (this *MemoryStorage) OpenWriter(key string, expiredAt int64, status int) ( } // 先删除 - err = this.deleteWithoutKey(key) + err = this.deleteWithoutLocker(key) if err != nil { return nil, err } @@ -276,7 +278,7 @@ func (this *MemoryStorage) memoryCapacityBytes() int64 { return c1 } -func (this *MemoryStorage) deleteWithoutKey(key string) error { +func (this *MemoryStorage) deleteWithoutLocker(key string) error { hash := this.hash(key) delete(this.valuesMap, hash) _ = this.list.Remove(fmt.Sprintf("%d", hash)) diff --git a/internal/caches/storage_memory_test.go b/internal/caches/storage_memory_test.go index f9d06b3..dbd7efa 100644 --- a/internal/caches/storage_memory_test.go +++ b/internal/caches/storage_memory_test.go @@ -84,6 +84,19 @@ func TestMemoryStorage_OpenWriter(t *testing.T) { } } +func TestMemoryStorage_OpenReaderLock(t *testing.T) { + storage := NewMemoryStorage(&serverconfigs.HTTPCachePolicy{}) + _ = storage.Init() + + var h = storage.hash("test") + storage.valuesMap = map[uint64]*MemoryItem{ + h: { + IsDone: true, + }, + } + _, _ = storage.OpenReader("test") +} + func TestMemoryStorage_Delete(t *testing.T) { storage := NewMemoryStorage(&serverconfigs.HTTPCachePolicy{}) { @@ -237,3 +250,18 @@ func TestMemoryStorage_Expire(t *testing.T) { } time.Sleep(70 * time.Second) } + +func TestMemoryStorage_Locker(t *testing.T) { + storage := NewMemoryStorage(&serverconfigs.HTTPCachePolicy{}) + err := storage.Init() + if err != nil { + t.Fatal(err) + } + storage.locker.Lock() + err = storage.deleteWithoutLocker("a") + storage.locker.Unlock() + if err != nil { + t.Fatal(err) + } + t.Log("ok") +}