Go and Redis

Find tutorials, examples and technical articles that will help you to develop with Redis and Golang.

Getting Started#

Golang community has built many client libraries that you can find here. For your first steps with Golang and Redis, this article will show how to use the recommended library: redigo.

The redigo library is located in the https://github.com/gomodule/redigo that you must import in your application.

Step 1. Import the redigo module#

go get github.com/gomodule/redigo/redis
import (
"fmt"
"context"
"github.com/gomodule/redigo/redis"
)

Step 2. Create a connection pool#

func newPool() *redis.Pool {
return &redis.Pool{
MaxIdle: 80,
MaxActive: 12000,
Dial: func() (redis.Conn, error) {
c, err := redis.Dial("tcp", ":6379")
if err != nil {
panic(err.Error())
}
return c, err
},
}
}

Step 3. Write your application code#

package main
import (
"fmt"
"github.com/gomodule/redigo/redis"
)
var pool = newPool()
func main() {
client := pool.Get()
defer client.Close()
_, err := client.Do("SET", "mykey", "Hello from redigo!")
if err != nil {
panic(err)
}
value, err := client.Do("GET", "mykey")
if err != nil {
panic(err)
}
fmt.Printf("%s \n", value)
_, err = client.Do("ZADD", "vehicles", 4, "car")
if err != nil {
panic(err)
}
_, err = client.Do("ZADD", "vehicles", 2, "bike")
if err != nil {
panic(err)
}
vehicles, err := client.Do("ZRANGE", "vehicles", 0, -1, "WITHSCORES")
if err != nil {
panic(err)
}
fmt.Printf("%s \n", vehicles)
}
func newPool() *redis.Pool {
return &redis.Pool{
MaxIdle: 80,
MaxActive: 12000,
Dial: func() (redis.Conn, error) {
c, err := redis.Dial("tcp", ":6379")
if err != nil {
panic(err.Error())
}
return c, err
},
}
}

Find more information about Golang & Redis connections in the "Redis Connect".

Technical Articles & Whitepapers#

Redis and Golang: Designed to Improve Performance

A High Performance Recommendation Engine with Redis and Go