Connect to Aiven for Valkey™ with Go
Establish a connection to the Aiven for Valkey™ service using Go. This example demonstrates how to connect to Aiven for Valkey from Go using the go-valkey/valkey library, designed to interact with the Valkey protocol.
Variables
Replace placeholders in the code sample with values from your service overview page:
| Variable | Description |
|---|---|
SERVICE_URI | URI for the Aiven for Valkey service connection |
Prerequisites
Install the valkey-go library using the following command:
go get github.com/valkey-io/valkey-go
Set up and run
-
Create a file named
main.goand insert the code below, substituting the placeholder with your Aiven for Valkey URI:package mainimport ("context""fmt""github.com/valkey-io/valkey-go")var ctx = context.Background()func main() {valkeyURI := "SERVICE_URI"opts, err = valkey.ParseURL(valkeyURI)if err != nil {return panic(err)}client, err := valkey.NewClient(opts)if err != nil {panic(err)}defer client.Close()err = client.Do(ctx, client.B().Set().Key("key").Value("hello world").Nx().Build()).Error()if err != nil {panic(err)}value, err := client.Do(ctx, client.B().Get().Key("key").Build()).ToString()if err != nil {panic(err)}fmt.Println("The value of key is:", value)}This code creates a key named
keywith the valuehello worldwithout an expiration. It then retrieves this key from the Valkey service and outputs its value. -
Run the script using the following command:
go run main.goA successful connection displays:
The value of key is: hello world
Related pages
- For additional information, see valkey-go github repository.