github.com/qjfoidnh/BaiduPCS-Go@v0.0.0-20231011165705-caa18a3765f3/baidupcs/expires/cachemap/cachemap_test.go (about) 1 package cachemap_test 2 3 import ( 4 "fmt" 5 "github.com/qjfoidnh/BaiduPCS-Go/baidupcs/expires" 6 "github.com/qjfoidnh/BaiduPCS-Go/baidupcs/expires/cachemap" 7 "sync" 8 "sync/atomic" 9 "testing" 10 "time" 11 ) 12 13 func TestCacheMapDataExpires(t *testing.T) { 14 cm := cachemap.CacheOpMap{} 15 cache := cm.LazyInitCachePoolOp("op") 16 cache.Store("key_1", expires.NewDataExpires("value_1", 1*time.Second)) 17 18 time.Sleep(2 * time.Second) 19 data, ok := cache.Load("key_1") 20 if ok { 21 fmt.Printf("data: %s\n", data.Data()) 22 // 超时仍能读取到数据, 失败 23 t.FailNow() 24 } 25 } 26 27 func TestCacheOperation(t *testing.T) { 28 cm := cachemap.CacheOpMap{} 29 data := cm.CacheOperation("op", "key_1", func() expires.DataExpires { 30 return expires.NewDataExpires("value_1", 1*time.Second) 31 }) 32 fmt.Printf("data: %s\n", data.Data()) 33 34 newData := cm.CacheOperation("op", "key_1", func() expires.DataExpires { 35 return expires.NewDataExpires("value_3", 1*time.Second) 36 }) 37 if data != newData { 38 t.FailNow() 39 } 40 fmt.Printf("data: %s\n", data.Data()) 41 } 42 43 func TestCacheOperation_LockKey(t *testing.T) { 44 cm := cachemap.CacheOpMap{} 45 wg := sync.WaitGroup{} 46 wg.Add(5000) 47 48 var ( 49 execTimes1 int32 = 0 // 执行次数1 50 execTimes2 int32 = 0 // 执行次数2 51 ) 52 53 for i := 0; i < 5000; i++ { 54 go func(i int) { 55 defer wg.Done() 56 cm.CacheOperation("op", "key_1", func() expires.DataExpires { 57 time.Sleep(50 * time.Microsecond) // 一些耗时的操作 58 atomic.AddInt32(&execTimes1, 1) 59 return expires.NewDataExpires(fmt.Sprintf("value_1: %d", i), 10*time.Second) 60 }) 61 62 cm.CacheOperation("op", "key_2", func() expires.DataExpires { 63 time.Sleep(50 * time.Microsecond) // 一些耗时的操作 64 atomic.AddInt32(&execTimes2, 1) 65 return expires.NewDataExpires(fmt.Sprintf("value_2: %d", i), 10*time.Second) 66 }) 67 }(i) 68 } 69 wg.Wait() 70 71 // 执行次数应为1 72 if execTimes1 != 1 { 73 fmt.Printf("execTimes1: %d\n", execTimes1) 74 t.FailNow() 75 } 76 if execTimes2 != 1 { 77 fmt.Printf("execTimes2: %d\n", execTimes2) 78 t.FailNow() 79 } 80 }