Updated on 2024-10-28 GMT+08:00

Connecting to Redis on go-redis (Go)

This section describes how to access a Redis instance on go-redis. For more information about how to use other Redis clients, visit the Redis official website.

The following operations are based on an example of accessing a Redis instance on a client on an elastic cloud server (ECS).

Prerequisites

Connecting to Redis on go-redis

  1. Log in to the ECS.

    A Windows ECS is used as an example.

  2. Install Visual Studio Community 2017 on the ECS.
  3. Start Visual Studio and create a project. The project name can be customized. In this example, the project name is set to redisdemo.
  4. Import the dependency package of go-redis and enter go get github.com/go-redis/redis on the terminal.
  5. Write the following code:

    package main
    
    import (
    	"fmt"
    	"github.com/go-redis/redis"
    )
    
    func main() {
    	// Single-node
    	rdb := redis.NewClient(&redis.Options{
    		Addr:     "host:port",
    		Password: "********", // no password set
    		DB:       0,  // use default DB
    	})
    
    	val, err := rdb.Get("key").Result()
    	if err != nil {
    		if err == redis.Nil {
    			fmt.Println("key does not exists")
    			return
    		}
    		panic(err)
    	}
    	fmt.Println(val)
    
    	//Cluster
    	rdbCluster := redis.NewClusterClient(&redis.ClusterOptions{
    		Addrs:    []string{"host:port"},
    		Password: "********",
    	})
    	val1, err1 := rdbCluster.Get("key").Result()
    	if err1 != nil {
    		if err == redis.Nil {
    			fmt.Println("key does not exists")
    			return
    		}
    		panic(err)
    	}
    	fmt.Println(val1)
    }

    host:port are the IP address/domain name and port number of the DCS Redis instance. For details about how to obtain the IP address/domain name and port, see Prerequisites. Change them as required. ******** indicates the password used to log in to the DCS Redis instance. This password is defined during DCS Redis instance creation.

  6. Run the go build -o test main.go command to package the code into an executable file, for example, test.

    To run the package in the Linux OS, set the following parameters before packaging:

    set GOARCH=amd64

    set GOOS=linux

  7. Run the ./test command to access the DCS instance.