go-redis / cache

Cache library with Redis backend for Golang
https://redis.uptrace.dev/guide/go-redis-cache.html
BSD 2-Clause "Simplified" License
750 stars 95 forks source link

Using TinyLFU doesn't work as you would expect a cache to #105

Open arielitovsky opened 9 months ago

arielitovsky commented 9 months ago

I expected that using TinyLFU would overwrite a value when setting it, just like Redis. However, overwriting a value doesn't seem to work. From what I can gather of the TinyLFU internals, it doesn't evict the old value.

Example test:

import (
    "context"
    "testing"
    "time"

    "github.com/go-redis/cache/v9"
    "github.com/stretchr/testify/assert"
)

func Test_TinyLFU(t *testing.T) {

    cacheClient := cache.New(&cache.Options{
        LocalCache: cache.NewTinyLFU(10, time.Minute*30),
    })
    key := "key-1"
    ctx := context.Background()

    // pos1
    pos1 := 1
    err := cacheClient.Set(&cache.Item{
        Key:   key,
        Value: pos1,
    })
    assert.NoError(t, err)
    var result int
    err = cacheClient.Get(ctx, key, &result)
    assert.NoError(t, err)
    assert.Equal(t, pos1, result)

    // pos 2
    pos2 := 2
    err = cacheClient.Set(&cache.Item{
        Key:   key,
        Value: pos2,
    })
    assert.NoError(t, err)
    var result2 int
    err = cacheClient.Get(ctx, key, &result2)
    assert.NoError(t, err)
    // The following test is erroring
    // Error:       Not equal:
    // expected: 2
    // actual  : 1
    // Test:        Test_TinyLFU
    assert.Equal(t, pos2, result2)
}
wsy6543 commented 4 months ago

this is shit,set twice and get nil

func TestTinyLFU(t *testing.T) { lfu := cache.NewTinyLFU(100, 300) lfu.Set("a", []byte("a")) lfu.Set("a", []byte("b")) lfu.Set("a", []byte("c")) value, ok := lfu.Get("a")

if !ok {
    t.Errorf("expected=true got=false")
}
if string(value) != "c" {
    t.Errorf("expected=c got=%s", value)
}

}