redis.go38 lines, 1.2 KB
| 1 | // Package redis connects services to Redis. |
| 2 | package redis |
| 3 | |
| 4 | import ( |
| 5 | "context" |
| 6 | "fmt" |
| 7 | "log/slog" |
| 8 | "time" |
| 9 | |
| 10 | goredis "github.com/redis/go-redis/v9" |
| 11 | ) |
| 12 | |
| 13 | // NewClient returns a client for the Redis server at url, like |
| 14 | // redis://localhost:6379/0. It connects lazily, and reconnects by itself, so a |
| 15 | // Redis that's down now is used again as soon as it's back. |
| 16 | func NewClient(url string) (*goredis.Client, error) { |
| 17 | opts, err := goredis.ParseURL(url) |
| 18 | if err != nil { |
| 19 | return nil, fmt.Errorf("redis: parse url: %w", err) |
| 20 | } |
| 21 | // We only use Redis as a cache, so it must fail fast, without retries: a |
| 22 | // slow cache that makes every request slow is worse than no cache at all. |
| 23 | opts.DialTimeout = 500 * time.Millisecond |
| 24 | opts.ReadTimeout = 200 * time.Millisecond |
| 25 | opts.WriteTimeout = 200 * time.Millisecond |
| 26 | opts.DialerRetries = 1 |
| 27 | opts.MaxRetries = -1 |
| 28 | goredis.SetLogger(logger{}) |
| 29 | return goredis.NewClient(opts), nil |
| 30 | } |
| 31 | |
| 32 | // logger sends go-redis's own log lines to slog, at debug level: our code |
| 33 | // already logs every failure that matters, with the request's context. |
| 34 | type logger struct{} |
| 35 | |
| 36 | func (logger) Printf(ctx context.Context, format string, v ...any) { |
| 37 | slog.DebugContext(ctx, fmt.Sprintf(format, v...), "component", "go-redis") |
| 38 | } |