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)