@@ -2,6 +2,8 @@ package caching_test
22
33import (
44 "context"
5+ "errors"
6+ "sync"
57 "testing"
68 "time"
79
@@ -11,13 +13,17 @@ import (
1113 "github.com/omalloc/contrib/kratos/caching"
1214)
1315
14- func fakeRefresh () map [int64 ]string {
16+ func fakeRefresh () ( map [int64 ]string , error ) {
1517 key := time .Now ().Unix ()
1618
19+ if key % 2 == 0 {
20+ return nil , errors .New ("error" )
21+ }
22+
1723 return map [int64 ]string {
1824 key - 1 : "new-value1" ,
1925 key : "new-value2" ,
20- }
26+ }, nil
2127}
2228
2329func TestBaseCache (t * testing.T ) {
@@ -59,21 +65,25 @@ func TestCacheChanged(t *testing.T) {
5965 caching.WithSize [int64 , string ](100 ),
6066 caching.WithExpiration [int64 , string ](2 * time .Second ), // 每2秒刷新一次缓存
6167 caching .WithRefreshAfterWrite (fakeRefresh ),
68+ caching .WithBlock [int64 , string ](),
6269 )
6370
6471 ctx , cancel := context .WithTimeout (context .Background (), 100 * time .Microsecond )
6572 defer cancel ()
6673
6774 // get all
6875 kvs := cc .GetALL (ctx )
69- assert .Equal (t , 0 , len (kvs ))
76+ assert .Equal (t , 2 , len (kvs ))
7077
7178 // set key 1
72- cc .Set (ctx , 1 , "value1" )
79+ _ = cc .Set (ctx , 1 , "value1" )
7380
7481 v , _ := cc .Get (ctx , 1 )
7582 assert .Equal (t , "value1" , v )
7683
84+ kvs = cc .GetALL (ctx )
85+ assert .Equal (t , 3 , len (kvs ))
86+
7787 // auto refresh
7888 time .Sleep (time .Second * 3 )
7989
@@ -155,3 +165,35 @@ func TestAutoRefresh(t *testing.T) {
155165 time .Sleep (time .Second * 3 )
156166 assert .Equal (t , 2 , len (cc .Values (ctx )))
157167}
168+
169+ func TestConcurrent (t * testing.T ) {
170+ cc := caching .New (
171+ caching.WithSize [int64 , string ](100 ),
172+ caching.WithExpiration [int64 , string ](2 * time .Second ), // 每2秒刷新一次缓存
173+ caching .WithRefreshAfterWrite (fakeRefresh ), // 每次请求刷出 2 个 kv
174+ caching .WithBlock [int64 , string ](),
175+ )
176+
177+ ctx , cancel := context .WithTimeout (context .Background (), 500 * time .Microsecond )
178+ defer cancel ()
179+
180+ wg := sync.WaitGroup {}
181+ wg .Add (20 )
182+
183+ for i := 0 ; i < 20 ; i ++ {
184+ go func () {
185+ for j := range 100 {
186+ t .Logf ("i: %d -> j: %d" , i , j )
187+ kvs := cc .GetALL (ctx )
188+ if len (kvs ) != 2 {
189+ panic ("kvs is not two-size." )
190+ }
191+ time .Sleep (time .Millisecond * 100 )
192+ }
193+ wg .Done ()
194+ }()
195+ }
196+
197+
198+ wg .Wait ()
199+ }
0 commit comments