Skip to content

Commit f0c4fb0

Browse files
committed
auto delete element from kv cache when unlock
1 parent 7e15aa4 commit f0c4fb0

File tree

5 files changed

+39
-2
lines changed

5 files changed

+39
-2
lines changed

.travis.yml

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
language: go
22

33
go:
4-
- "1.11.x"
5-
- "1.12"
4+
- "1.13"
5+
- "1.14"
6+
- "1.15"
67

78
before_install:
89
- go get github.com/mattn/goveralls

go.mod

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
module github.com/amyangfei/redlock-go
22

3+
go 1.15
4+
35
require (
46
github.com/davecgh/go-spew v1.1.1 // indirect
57
github.com/go-redis/redis v6.14.2+incompatible

redlock/kvcache.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,9 @@ type KVCache interface {
2828
// Delete removes the LockElem with given key from storage
2929
Delete(key string)
3030

31+
// Size returns element count in kv storage
32+
Size() int
33+
3134
// GC cleans the expired LockElem stored in storage
3235
GC()
3336
}
@@ -77,6 +80,13 @@ func (sc *SimpleCache) Delete(key string) {
7780
delete(sc.kvs, key)
7881
}
7982

83+
// Size implements KVCache.Size
84+
func (sc *SimpleCache) Size() int {
85+
sc.lock.RLock()
86+
defer sc.lock.RUnlock()
87+
return len(sc.kvs)
88+
}
89+
8090
// GC implements KVCache.GC
8191
func (sc *SimpleCache) GC() {
8292
sc.lock.Lock()

redlock/redlock.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,7 @@ func (r *RedLock) UnLock(resource string) error {
216216
if elem == nil {
217217
return nil
218218
}
219+
defer r.cache.Delete(resource)
219220
c := make(chan bool, len(r.clients))
220221
for _, cli := range r.clients {
221222
go unlockInstance(cli, resource, elem.val, c)

redlock/redlock_test.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -226,3 +226,26 @@ func TestAcquireLockFailed(t *testing.T) {
226226

227227
wg.Wait()
228228
}
229+
230+
func TestKVCache(t *testing.T) {
231+
lock, err := NewRedLock(redisServers)
232+
assert.Nil(t, err)
233+
234+
var wg sync.WaitGroup
235+
for i := 0; i < 4; i++ {
236+
wg.Add(1)
237+
i := i
238+
go func() {
239+
defer wg.Done()
240+
for j := 0; j < 100; j++ {
241+
key := fmt.Sprintf("foo-%d-%d", i, j)
242+
_, err = lock.Lock(key, 200)
243+
assert.Nil(t, err)
244+
err = lock.UnLock(key)
245+
assert.Nil(t, err)
246+
}
247+
}()
248+
}
249+
wg.Done()
250+
assert.Zero(t, lock.cache.Size())
251+
}

0 commit comments

Comments
 (0)