feat(redis): add namespace counter key

This commit is contained in:
tiennm99 committed 2026-06-28 19:35:06 +07:00
1 parent 77b08464b0
commit 8108288dca
4 files changed
+67 -3

No files matched your search

+10 -1
View File
@@ -2,6 +2,7 @@ package adapter
import (
"context"
"strings"
"github.com/redis/go-redis/v9"
)
@@ -14,7 +15,7 @@ func init() {
}
return &redisAdapter{
url: url,
key: cfg.Optional("counter_key", "counter"),
key: redisCounterKey(cfg.Optional("counter_key", "counter"), cfg.Optional("namespace", "")),
}, nil
}
}
@@ -52,3 +53,11 @@ func (a *redisAdapter) Close(_ context.Context) error {
}
return a.client.Close()
}
func redisCounterKey(counterKey, namespace string) string {
namespace = strings.TrimSpace(namespace)
if namespace == "" {
return counterKey
}
return namespace + ":" + counterKey
}
+52
View File
@@ -0,0 +1,52 @@
package adapter
import "testing"
func TestRedisFactoryUsesRootCounterKeyWithoutNamespace(t *testing.T) {
got := newRedisAdapterForTest(t, Config{
"url": "redis://cache.example.com:6379",
"counter_key": "counter",
})
if got.key != "counter" {
t.Fatalf("key = %q, want %q", got.key, "counter")
}
}
func TestRedisFactoryPrefixesCounterKeyWithNamespace(t *testing.T) {
got := newRedisAdapterForTest(t, Config{
"url": "redis://cache.example.com:6379",
"counter_key": "counter",
"namespace": "keepalive",
})
if got.key != "keepalive:counter" {
t.Fatalf("key = %q, want %q", got.key, "keepalive:counter")
}
}
func TestRedisFactoryTreatsBlankNamespaceAsRoot(t *testing.T) {
got := newRedisAdapterForTest(t, Config{
"url": "redis://cache.example.com:6379",
"counter_key": "counter",
"namespace": " ",
})
if got.key != "counter" {
t.Fatalf("key = %q, want %q", got.key, "counter")
}
}
func newRedisAdapterForTest(t *testing.T, cfg Config) *redisAdapter {
t.Helper()
adapterValue, err := Registry["redis"](cfg)
if err != nil {
t.Fatalf("redis factory returned error: %v", err)
}
got, ok := adapterValue.(*redisAdapter)
if !ok {
t.Fatalf("redis factory returned %T, want *redisAdapter", adapterValue)
}
return got
}