From 39bd40e512fad75af4739b93c6ed13734d7fc899 Mon Sep 17 00:00:00 2001 From: "Edward.Yang" Date: Wed, 1 May 2019 13:10:21 +0800 Subject: [PATCH] =?UTF-8?q?Incr=E5=92=8CDecr=E5=BA=94=E8=AF=A5=E6=94=B9?= =?UTF-8?q?=E6=88=90=E6=8E=92=E5=AE=83=E9=94=81=EF=BC=8C=E5=90=A6=E5=88=99?= =?UTF-8?q?=E5=9C=A8=E5=B9=B6=E5=8F=91=E7=9A=84=E6=97=B6=E5=80=99=E4=BC=9A?= =?UTF-8?q?=E5=87=BA=E7=8E=B0=E9=9D=9E=E6=9C=9F=E6=9C=9B=E7=9A=84=E7=BB=93?= =?UTF-8?q?=E6=9E=9C=E5=80=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cache/cache_test.go | 23 +++++++++++++++++++++++ cache/memory.go | 8 ++++---- 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/cache/cache_test.go b/cache/cache_test.go index 1e71d075..470c0a43 100644 --- a/cache/cache_test.go +++ b/cache/cache_test.go @@ -16,10 +16,33 @@ package cache import ( "os" + "sync" "testing" "time" ) +func TestCacheIncr(t *testing.T) { + bm, err := NewCache("memory", `{"interval":20}`) + if err != nil { + t.Error("init err") + } + //timeoutDuration := 10 * time.Second + + bm.Put("edwardhey", 0, time.Second*20) + wg := sync.WaitGroup{} + wg.Add(10) + for i := 0; i < 10; i++ { + go func() { + defer wg.Done() + bm.Incr("edwardhey") + }() + } + wg.Wait() + if bm.Get("edwardhey").(int) != 10 { + t.Error("Incr err") + } +} + func TestCache(t *testing.T) { bm, err := NewCache("memory", `{"interval":20}`) if err != nil { diff --git a/cache/memory.go b/cache/memory.go index e5b562f0..1fec2eff 100644 --- a/cache/memory.go +++ b/cache/memory.go @@ -110,8 +110,8 @@ func (bc *MemoryCache) Delete(name string) error { // Incr increase cache counter in memory. // it supports int,int32,int64,uint,uint32,uint64. func (bc *MemoryCache) Incr(key string) error { - bc.RLock() - defer bc.RUnlock() + bc.Lock() + defer bc.Unlock() itm, ok := bc.items[key] if !ok { return errors.New("key not exist") @@ -137,8 +137,8 @@ func (bc *MemoryCache) Incr(key string) error { // Decr decrease counter in memory. func (bc *MemoryCache) Decr(key string) error { - bc.RLock() - defer bc.RUnlock() + bc.Lock() + defer bc.Unlock() itm, ok := bc.items[key] if !ok { return errors.New("key not exist")