Connect Redis from Golang


In this article i am not going to say how Redis and golang works, I hope you have basic knowledge of both. Instead I will tell you how to connect to redis server and execute command from golang. 

In case you don't have the knowledge on Redis & Golang please check their official websites (GOLANG & REDIS) for documentation and more information.

I believe you have already installed golang and redis server in your laptop/PC. If not please check their official website for installation procedure.

Redis server written in C programming language but it has client available for most of the programming language. There is more libraries available for golang as well. I am going to use Redigo because it has many feature and easy to use. You can check their github website [ Redigo github ] for source code and documents

You can download the Redigo redis client library for golang using the go get command like below
          go get github.com/garyburd/redigo/redis
You should configure GOPATH environment variable to succeed this command.

Here I provide the simple program to connect redis server from golang and query redis SET & GET command.

Example Program:

package main

import (
    "fmt"
    "github.com/garyburd/redigo/redis"
    "log"
)

func main() {
    /* Connect With Redis Server */
    r, err := redis.Dial("tcp", ":7777")
    if err != nil {
        fmt.Println("Error ", err)
    }
    fmt.Println("Connection Success With Redis Server")

    /* Query Redis Commands */
    _, err = r.Do("SET", "Name1", "Michel")
    if err != nil {
        log.Fatal("Error to SET", err)
    }
    fmt.Println("SET Success")

    value, err := redis.String(r.Do("Get", "Name1"))
    if err != nil {
        log.Fatal("Error to GET", err)
    }
    fmt.Println("GET Success: Name1 =", value)

    /* Close Redis Server Connection*/
    r.Close()

}

Output:

Connection Success With Redis Server
SET Success

GET Success: Name1 = Michel


Source Code Explanation:

In this example code i used two redigo api calls Dial which help to connect redis server and Do execute redis command.

r, err := redis.Dial("tcp", ":7777")

This statement connect help to connect your redis server running in port number 7777 using tcp connection. It return error and redis handler which help for other redigo APIs.

    _, err = r.Do("SET", "Name1", "Michel")

DO api will execute redis SET command with key as "Name1" and value as "Michel". Here "r" is handle returned from previous Dial API. This statement is similar to executing redis command "SET Name1 Michel" from redis CLI client.

    value, err := redis.String(r.Do("Get", "Name1"))

This statement get the redis key with name as "Name1" and convert to string format. This is similar to executing "GET NAME1" .

    r.Close()

This statement used to close redis connection.

No comments:

Post a Comment