diff --git a/README.md b/README.md index c5789cc..5916656 100644 --- a/README.md +++ b/README.md @@ -15,14 +15,14 @@ one) to recover from downtime quickly. (See the docs for `NewFrom()` for caveats ### Installation -`go get github.com/patrickmn/go-cache` +`go get github.com/youjianglong/go-cache` ### Usage ```go import ( "fmt" - "github.com/patrickmn/go-cache" + "github.com/youjianglong/go-cache" "time" ) @@ -80,4 +80,4 @@ func main() { ### Reference -`godoc` or [http://godoc.org/github.com/patrickmn/go-cache](http://godoc.org/github.com/patrickmn/go-cache) +`godoc` or [http://godoc.org/github.com/youjianglong/go-cache](http://godoc.org/github.com/youjianglong/go-cache) diff --git a/cache.go b/cache.go index db88d2f..72ccf93 100644 --- a/cache.go +++ b/cache.go @@ -165,6 +165,37 @@ func (c *cache) GetWithExpiration(k string) (interface{}, time.Time, bool) { return item.Object, time.Time{}, true } +// Iterate every item by item handle items from cache,and if the handle returns to false, +// it will be interrupted and return false. +func (c *cache) Iterate(f func(key string, item Item) bool) bool { + now := time.Now().UnixNano() + c.mu.RLock() + keys := make([]string, len(c.items)) + i := 0 + for k, v := range c.items { + // "Inlining" of Expired + if v.Expiration > 0 && now > v.Expiration { + continue + } + keys[i] = k + i++ + } + c.mu.RUnlock() + keys = keys[:i] + for _, key := range keys { + c.mu.RLock() + item, ok := c.items[key] + c.mu.RUnlock() + if !ok { + continue + } + if !f(key, item) { + return false + } + } + return true +} + func (c *cache) get(k string) (interface{}, bool) { item, found := c.items[k] if !found { diff --git a/cache_test.go b/cache_test.go index 47a3d53..a528468 100644 --- a/cache_test.go +++ b/cache_test.go @@ -1555,7 +1555,7 @@ func benchmarkCacheGetManyConcurrent(b *testing.B, exp time.Duration) { tc := New(exp, 0) keys := make([]string, n) for i := 0; i < n; i++ { - k := "foo" + strconv.Itoa(n) + k := "foo" + strconv.Itoa(i) keys[i] = k tc.Set(k, "bar", DefaultExpiration) } diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..e510a33 --- /dev/null +++ b/go.mod @@ -0,0 +1 @@ +module github.com/youjianglong/go-cache diff --git a/sharded_test.go b/sharded_test.go index aef8597..c1ce7ab 100644 --- a/sharded_test.go +++ b/sharded_test.go @@ -65,7 +65,7 @@ func benchmarkShardedCacheGetManyConcurrent(b *testing.B, exp time.Duration) { tsc := unexportedNewSharded(exp, 0, 20) keys := make([]string, n) for i := 0; i < n; i++ { - k := "foo" + strconv.Itoa(n) + k := "foo" + strconv.Itoa(i) keys[i] = k tsc.Set(k, "bar", DefaultExpiration) }