1
0
mirror of https://github.com/go-micro/go-micro.git synced 2025-06-06 22:06:19 +02:00
go-micro/cache/redis/options.go

49 lines
1.1 KiB
Go
Raw Normal View History

2025-05-15 12:25:04 -04:00
package redis
2025-05-07 20:43:54 -04:00
import (
"context"
2025-05-15 12:25:04 -04:00
rclient "github.com/go-redis/redis/v8"
2025-05-07 20:43:54 -04:00
"go-micro.dev/v5/cache"
)
type redisOptionsContextKey struct{}
// WithRedisOptions sets advanced options for redis.
2025-05-15 12:25:04 -04:00
func WithRedisOptions(options rclient.UniversalOptions) cache.Option {
2025-05-07 20:43:54 -04:00
return func(o *cache.Options) {
if o.Context == nil {
o.Context = context.Background()
}
o.Context = context.WithValue(o.Context, redisOptionsContextKey{}, options)
}
}
2025-05-15 12:25:04 -04:00
func newUniversalClient(options cache.Options) rclient.UniversalClient {
2025-05-07 20:43:54 -04:00
if options.Context == nil {
options.Context = context.Background()
}
2025-05-15 12:25:04 -04:00
opts, ok := options.Context.Value(redisOptionsContextKey{}).(rclient.UniversalOptions)
2025-05-07 20:43:54 -04:00
if !ok {
addr := "redis://127.0.0.1:6379"
if len(options.Address) > 0 {
addr = options.Address
}
2025-05-15 12:25:04 -04:00
redisOptions, err := rclient.ParseURL(addr)
2025-05-07 20:43:54 -04:00
if err != nil {
2025-05-15 12:25:04 -04:00
redisOptions = &rclient.Options{Addr: addr}
2025-05-07 20:43:54 -04:00
}
2025-05-15 12:25:04 -04:00
return rclient.NewClient(redisOptions)
2025-05-07 20:43:54 -04:00
}
if len(opts.Addrs) == 0 && len(options.Address) > 0 {
opts.Addrs = []string{options.Address}
}
2025-05-15 12:25:04 -04:00
return rclient.NewUniversalClient(&opts)
2025-05-07 20:43:54 -04:00
}