Connect to the server
Connect your Go application to a Redis database
Basic connection
The following example shows the simplest way to connect to a Redis server:
import (
"context"
"fmt"
"github.com/redis/go-redis/v9"
)
func main() {
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // No password set
DB: 0, // Use default DB
Protocol: 2, // Connection protocol
})
}
You can also connect using a connection string:
opt, err := redis.ParseURL("redis://<user>:<pass>@localhost:6379/<db>")
if err != nil {
panic(err)
}
client := redis.NewClient(opt)
After connecting, you can test the connection by storing and retrieving a simple string:
ctx := context.Background()
err := client.Set(ctx, "foo", "bar", 0).Err()
if err != nil {
panic(err)
}
val, err := client.Get(ctx, "foo").Result()
if err != nil {
panic(err)
}
fmt.Println("foo", val)
Connect to a Redis cluster
To connect to a Redis cluster, use NewClusterClient(). You can specify
one or more cluster endpoints with the Addrs option:
client := redis.NewClusterClient(&redis.ClusterOptions{
Addrs: []string{":16379", ":16380", ":16381", ":16382", ":16383", ":16384"},
// To route commands by latency or randomly, enable one of the following.
//RouteByLatency: true,
//RouteRandomly: true,
})
Connect to your production Redis with TLS
When you deploy your application, use TLS and follow the Redis security guidelines.
Establish a secure connection with your Redis database:
// Load client cert
cert, err := tls.LoadX509KeyPair("redis_user.crt", "redis_user_private.key")
if err != nil {
log.Fatal(err)
}
// Load CA cert
caCert, err := os.ReadFile("redis_ca.pem")
if err != nil {
log.Fatal(err)
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
client := redis.NewClient(&redis.Options{
Addr: "my-redis.cloud.redislabs.com:6379",
Username: "default", // use your Redis user. More info https://redis.io/docs/latest/operate/oss_and_stack/management/security/acl/
Password: "secret", // use your Redis password
TLSConfig: &tls.Config{
MinVersion: tls.VersionTLS12,
Certificates: []tls.Certificate{cert},
RootCAs: caCertPool,
},
})
//send SET command
err = client.Set(ctx, "foo", "bar", 0).Err()
if err != nil {
panic(err)
}
//send GET command and print the value
val, err := client.Get(ctx, "foo").Result()
if err != nil {
panic(err)
}
fmt.Println("foo", val)
Connect using Smart client handoffs (SCH)
Smart client handoffs (SCH) is a feature of Redis Cloud and Redis Software servers that lets them actively notify clients about planned server maintenance shortly before it happens. This lets a client take action to avoid disruptions in service. See Smart client handoffs for more information about SCH.
By default, go-redis always attempts to connect via SCH but falls back to
a non-SCH connection if the server doesn't support it. However, you can configure SCH
explicitly by passing a MaintNotificationsConfig object during the connection,
as shown in the following example:
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Protocol: 3, // RESP3 required
MaintNotificationsConfig: &maintnotifications.Config{
Mode: maintnotifications.ModeEnabled,
EndpointType: maintnotifications.EndpointTypeExternalIP,
HandoffTimeout: 10 * time.Second,
RelaxedTimeout: 10 * time.Second,
PostHandoffRelaxedDuration: 10 * time.Second,
MaxHandoffRetries: 5,
},
})
The maintnotifications.Config object accepts the following parameters:
| Name | Description |
|---|---|
Mode |
Whether or not to enable SCH. The options are ModeDisabled, ModeEnabled (require SCH and abort the connection if not supported), and ModeAuto (require SCH and fall back to a non-SCH connection if not supported). The default is ModeAuto. |
EndpointType |
The type of endpoint to use for the connection. The options are EndpointTypeExternalIP, EndpointTypeInternalIP, EndpointTypeExternalFQDN, EndpointTypeInternalFQDN, EndpointTypeAuto (auto-detect based on connection), and EndpointTypeNone (reconnect with current config). The default is EndpointTypeExternalIP. |
HandoffTimeout |
The timeout to connect to the replacement node. The default is 15 seconds. |
RelaxedTimeout |
The timeout to use for commands and connections while the server is performing maintenance. The default is 10 seconds. |
PostHandoffRelaxedDuration |
The duration to continue using relaxed timeouts after a successful handoff (this provides extra resilience during cluster transitions). The default is 20 seconds. |
MaxHandoffRetries |
The maximum number of times to retry connecting to the replacement node. The default is 3. |
EndpointType: maintnotifications.EndpointTypeNone
when you connect. All other configurations have full support for both relaxed timeouts and pre-handoffs.