Files
keepalive/adapter/redis.go
T
tiennm99 cbcee9ccd8 refactor(adapter)!: drop the valkey adapter in favor of redis
Valkey speaks the Redis protocol, so the redis adapter (go-redis) already
serves it. Dropping valkey-go removes a dependency and shrinks the stripped
binary by about 9 MB.

The redis adapter now also closes a client that failed to connect only once.

BREAKING CHANGE: `adapter: valkey` is no longer accepted. Use
`adapter: redis` with a redis:// or rediss:// URL instead of valkey:// or
valkeys://. The namespace option now applies to these services.
2026-10-09 11:10:44 +07:00

67 lines
1.3 KiB
Go

package adapter
import (
"context"
"strings"
"github.com/redis/go-redis/v9"
)
func init() {
Registry["redis"] = func(cfg Config) (Adapter, error) {
url, err := cfg.Required("url")
if err != nil {
return nil, err
}
return &redisAdapter{
url: url,
key: redisCounterKey(cfg.Optional("counter_key", "counter"), cfg.Optional("namespace", "")),
}, nil
}
}
// redisAdapter serves every RESP-compatible store: Redis, Valkey, Dragonfly,
// KeyDB, Garnet and their hosted variants.
type redisAdapter struct {
client *redis.Client
url string
key string
}
func (a *redisAdapter) Connect(ctx context.Context) error {
opt, err := redis.ParseURL(a.url)
if err != nil {
return err
}
client := redis.NewClient(opt)
if err := client.Ping(ctx).Err(); err != nil {
client.Close()
return err
}
if err := client.SetNX(ctx, a.key, 0, 0).Err(); err != nil {
client.Close()
return err
}
a.client = client
return nil
}
func (a *redisAdapter) Increment(ctx context.Context) (int64, error) {
return a.client.Incr(ctx, a.key).Result()
}
func (a *redisAdapter) Close(_ context.Context) error {
if a.client == nil {
return nil
}
return a.client.Close()
}
func redisCounterKey(counterKey, namespace string) string {
namespace = strings.TrimSpace(namespace)
if namespace == "" {
return counterKey
}
return namespace + ":" + counterKey
}