Skip to content

Commit 16918e9

Browse files
DOC-4543 split Go client page and removed Connect folder level
1 parent 6d2397b commit 16918e9

File tree

111 files changed

+524
-574
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

111 files changed

+524
-574
lines changed

content/develop/connect/clients/_index.md renamed to content/develop/clients/_index.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ categories:
1212
description: Connect your application to a Redis database and try an example
1313
linkTitle: Clients
1414
title: Connect with Redis clients
15-
weight: 45
15+
weight: 30
1616
---
1717

1818
Use the Redis client libraries to connect to Redis servers from
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Lines changed: 193 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,193 @@
1+
---
2+
categories:
3+
- docs
4+
- develop
5+
- stack
6+
- oss
7+
- rs
8+
- rc
9+
- oss
10+
- kubernetes
11+
- clients
12+
description: Connect your Go application to a Redis database
13+
linkTitle: Go
14+
title: Go guide
15+
weight: 5
16+
---
17+
18+
[`go-redis`](https://github.com/redis/go-redis) is the [Go](https://go.dev/) client for Redis.
19+
The sections below explain how to install `go-redis` and connect your application to a Redis database.
20+
21+
`go-redis` requires a running Redis or
22+
[Redis Stack]({{< relref "/operate/oss_and_stack/install/install-stack/" >}}) server.
23+
See [Getting started]({{< relref "/operate/oss_and_stack/install/" >}}) for Redis installation
24+
instructions.
25+
26+
## Install
27+
28+
`go-redis` supports the last two Go versions. You can only use it from within
29+
a Go module, so you must initialize a Go module before you start, or add your code to
30+
an existing module:
31+
32+
```
33+
go mod init github.com/my/repo
34+
```
35+
36+
Use the `go get` command to install `go-redis/v9`:
37+
38+
```
39+
go get github.com/redis/go-redis/v9
40+
```
41+
42+
## Connect
43+
44+
The following example shows the simplest way to connect to a Redis server:
45+
46+
```go
47+
import (
48+
"context"
49+
"fmt"
50+
"github.com/redis/go-redis/v9"
51+
)
52+
53+
func main() {
54+
client := redis.NewClient(&redis.Options{
55+
Addr: "localhost:6379",
56+
Password: "", // No password set
57+
DB: 0, // Use default DB
58+
Protocol: 2, // Connection protocol
59+
})
60+
}
61+
```
62+
63+
You can also connect using a connection string:
64+
65+
```go
66+
opt, err := redis.ParseURL("redis://<user>:<pass>@localhost:6379/<db>")
67+
if err != nil {
68+
panic(err)
69+
}
70+
71+
client := redis.NewClient(opt)
72+
```
73+
74+
After connecting, you can test the connection by storing and retrieving
75+
a simple [string]({{< relref "/develop/data-types/strings" >}}):
76+
77+
```go
78+
ctx := context.Background()
79+
80+
err := client.Set(ctx, "foo", "bar", 0).Err()
81+
if err != nil {
82+
panic(err)
83+
}
84+
85+
val, err := client.Get(ctx, "foo").Result()
86+
if err != nil {
87+
panic(err)
88+
}
89+
fmt.Println("foo", val)
90+
```
91+
92+
You can also easily store and retrieve a [hash]({{< relref "/develop/data-types/hashes" >}}):
93+
94+
```go
95+
hashFields := []string{
96+
"model", "Deimos",
97+
"brand", "Ergonom",
98+
"type", "Enduro bikes",
99+
"price", "4972",
100+
}
101+
102+
res1, err := rdb.HSet(ctx, "bike:1", hashFields).Result()
103+
104+
if err != nil {
105+
panic(err)
106+
}
107+
108+
fmt.Println(res1) // >>> 4
109+
110+
res2, err := rdb.HGet(ctx, "bike:1", "model").Result()
111+
112+
if err != nil {
113+
panic(err)
114+
}
115+
116+
fmt.Println(res2) // >>> Deimos
117+
118+
res3, err := rdb.HGet(ctx, "bike:1", "price").Result()
119+
120+
if err != nil {
121+
panic(err)
122+
}
123+
124+
fmt.Println(res3) // >>> 4972
125+
126+
res4, err := rdb.HGetAll(ctx, "bike:1").Result()
127+
128+
if err != nil {
129+
panic(err)
130+
}
131+
132+
fmt.Println(res4)
133+
// >>> map[brand:Ergonom model:Deimos price:4972 type:Enduro bikes]
134+
```
135+
136+
Use
137+
[struct tags](https://stackoverflow.com/questions/10858787/what-are-the-uses-for-struct-tags-in-go)
138+
of the form `redis:"<field-name>"` with the `Scan()` method to parse fields from
139+
a hash directly into corresponding struct fields:
140+
141+
```go
142+
type BikeInfo struct {
143+
Model string `redis:"model"`
144+
Brand string `redis:"brand"`
145+
Type string `redis:"type"`
146+
Price int `redis:"price"`
147+
}
148+
149+
var res4a BikeInfo
150+
err = rdb.HGetAll(ctx, "bike:1").Scan(&res4a)
151+
152+
if err != nil {
153+
panic(err)
154+
}
155+
156+
fmt.Printf("Model: %v, Brand: %v, Type: %v, Price: $%v\n",
157+
res4a.Model, res4a.Brand, res4a.Type, res4a.Price)
158+
// >>> Model: Deimos, Brand: Ergonom, Type: Enduro bikes, Price: $4972
159+
```
160+
161+
## Observability
162+
163+
`go-redis` supports [OpenTelemetry](https://opentelemetry.io/) instrumentation.
164+
to monitor performance and trace the execution of Redis commands.
165+
For example, the following code instruments Redis commands to collect traces, logs, and metrics:
166+
167+
```go
168+
import (
169+
"github.com/redis/go-redis/v9"
170+
"github.com/redis/go-redis/extra/redisotel/v9"
171+
)
172+
173+
rdb := redis.NewClient(&redis.Options{...})
174+
175+
// Enable tracing instrumentation.
176+
if err := redisotel.InstrumentTracing(rdb); err != nil {
177+
panic(err)
178+
}
179+
180+
// Enable metrics instrumentation.
181+
if err := redisotel.InstrumentMetrics(rdb); err != nil {
182+
panic(err)
183+
}
184+
```
185+
186+
See the `go-redis` [GitHub repo](https://github.com/redis/go-redis/blob/master/example/otel/README.md).
187+
for more OpenTelemetry examples.
188+
189+
## More information
190+
191+
See the other pages in this section for more information and examples.
192+
Further examples are available at the [`go-redis`](https://redis.uptrace.dev/guide/) website
193+
and the [GitHub repository](https://github.com/redis/go-redis).
Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
1+
---
2+
categories:
3+
- docs
4+
- develop
5+
- stack
6+
- oss
7+
- rs
8+
- rc
9+
- oss
10+
- kubernetes
11+
- clients
12+
description: Connect your Go application to a Redis database
13+
linkTitle: Connect
14+
title: Connect to the server
15+
weight: 1
16+
---
17+
18+
## Basic connection
19+
20+
## Connect
21+
22+
The following example shows the simplest way to connect to a Redis server:
23+
24+
```go
25+
import (
26+
"context"
27+
"fmt"
28+
"github.com/redis/go-redis/v9"
29+
)
30+
31+
func main() {
32+
client := redis.NewClient(&redis.Options{
33+
Addr: "localhost:6379",
34+
Password: "", // No password set
35+
DB: 0, // Use default DB
36+
Protocol: 2, // Connection protocol
37+
})
38+
}
39+
```
40+
41+
You can also connect using a connection string:
42+
43+
```go
44+
opt, err := redis.ParseURL("redis://<user>:<pass>@localhost:6379/<db>")
45+
if err != nil {
46+
panic(err)
47+
}
48+
49+
client := redis.NewClient(opt)
50+
```
51+
52+
After connecting, you can test the connection by storing and retrieving
53+
a simple [string]({{< relref "/develop/data-types/strings" >}}):
54+
55+
```go
56+
ctx := context.Background()
57+
58+
err := client.Set(ctx, "foo", "bar", 0).Err()
59+
if err != nil {
60+
panic(err)
61+
}
62+
63+
val, err := client.Get(ctx, "foo").Result()
64+
if err != nil {
65+
panic(err)
66+
}
67+
fmt.Println("foo", val)
68+
```
69+
70+
## Connect to a Redis cluster
71+
72+
To connect to a Redis cluster, use `NewClusterClient()`. You can specify
73+
one or more cluster endpoints with the `Addrs` option:
74+
75+
```go
76+
client := redis.NewClusterClient(&redis.ClusterOptions{
77+
Addrs: []string{":16379", ":16380", ":16381", ":16382", ":16383", ":16384"},
78+
79+
// To route commands by latency or randomly, enable one of the following.
80+
//RouteByLatency: true,
81+
//RouteRandomly: true,
82+
})
83+
```
84+
85+
## Connect to your production Redis with TLS
86+
87+
When you deploy your application, use TLS and follow the
88+
[Redis security]({{< relref "/operate/oss_and_stack/management/security/" >}}) guidelines.
89+
90+
Establish a secure connection with your Redis database:
91+
92+
```go
93+
// Load client cert
94+
cert, err := tls.LoadX509KeyPair("redis_user.crt", "redis_user_private.key")
95+
if err != nil {
96+
log.Fatal(err)
97+
}
98+
99+
// Load CA cert
100+
caCert, err := os.ReadFile("redis_ca.pem")
101+
if err != nil {
102+
log.Fatal(err)
103+
}
104+
caCertPool := x509.NewCertPool()
105+
caCertPool.AppendCertsFromPEM(caCert)
106+
107+
client := redis.NewClient(&redis.Options{
108+
Addr: "my-redis.cloud.redislabs.com:6379",
109+
Username: "default", // use your Redis user. More info https://redis.io/docs/latest/operate/oss_and_stack/management/security/acl/
110+
Password: "secret", // use your Redis password
111+
TLSConfig: &tls.Config{
112+
MinVersion: tls.VersionTLS12,
113+
Certificates: []tls.Certificate{cert},
114+
RootCAs: caCertPool,
115+
},
116+
})
117+
118+
//send SET command
119+
err = client.Set(ctx, "foo", "bar", 0).Err()
120+
if err != nil {
121+
panic(err)
122+
}
123+
124+
//send GET command and print the value
125+
val, err := client.Get(ctx, "foo").Result()
126+
if err != nil {
127+
panic(err)
128+
}
129+
fmt.Println("foo", val)
130+
```

0 commit comments

Comments
 (0)