Skip to content

Commit

Permalink
auto delete element from kv cache when unlock
Browse files Browse the repository at this point in the history
  • Loading branch information
amyangfei committed Oct 2, 2020
1 parent 7e15aa4 commit f0c4fb0
Show file tree
Hide file tree
Showing 5 changed files with 39 additions and 2 deletions.
5 changes: 3 additions & 2 deletions .travis.yml
@@ -1,8 +1,9 @@
language: go

go:
- "1.11.x"
- "1.12"
- "1.13"
- "1.14"
- "1.15"

before_install:
- go get github.com/mattn/goveralls
Expand Down
2 changes: 2 additions & 0 deletions go.mod
@@ -1,5 +1,7 @@
module github.com/amyangfei/redlock-go

go 1.15

require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/go-redis/redis v6.14.2+incompatible
Expand Down
10 changes: 10 additions & 0 deletions redlock/kvcache.go
Expand Up @@ -28,6 +28,9 @@ type KVCache interface {
// Delete removes the LockElem with given key from storage
Delete(key string)

// Size returns element count in kv storage
Size() int

// GC cleans the expired LockElem stored in storage
GC()
}
Expand Down Expand Up @@ -77,6 +80,13 @@ func (sc *SimpleCache) Delete(key string) {
delete(sc.kvs, key)
}

// Size implements KVCache.Size
func (sc *SimpleCache) Size() int {
sc.lock.RLock()
defer sc.lock.RUnlock()
return len(sc.kvs)
}

// GC implements KVCache.GC
func (sc *SimpleCache) GC() {
sc.lock.Lock()
Expand Down
1 change: 1 addition & 0 deletions redlock/redlock.go
Expand Up @@ -216,6 +216,7 @@ func (r *RedLock) UnLock(resource string) error {
if elem == nil {
return nil
}
defer r.cache.Delete(resource)
c := make(chan bool, len(r.clients))
for _, cli := range r.clients {
go unlockInstance(cli, resource, elem.val, c)
Expand Down
23 changes: 23 additions & 0 deletions redlock/redlock_test.go
Expand Up @@ -226,3 +226,26 @@ func TestAcquireLockFailed(t *testing.T) {

wg.Wait()
}

func TestKVCache(t *testing.T) {
lock, err := NewRedLock(redisServers)
assert.Nil(t, err)

var wg sync.WaitGroup
for i := 0; i < 4; i++ {
wg.Add(1)
i := i
go func() {
defer wg.Done()
for j := 0; j < 100; j++ {
key := fmt.Sprintf("foo-%d-%d", i, j)
_, err = lock.Lock(key, 200)
assert.Nil(t, err)
err = lock.UnLock(key)
assert.Nil(t, err)
}
}()
}
wg.Done()
assert.Zero(t, lock.cache.Size())
}

0 comments on commit f0c4fb0

Please sign in to comment.