How to use Redis as a database

7.9K views
6 min read

Redis is short for remote dictionary server. It’s an in-memory data structure store that supports lists, strings, maps, streams, sets, and other structures for storing abstract data.

While Redis is a full-on primary database, it’s a NoSQL one. It’s one of the best loved NoSQL solutions and one of the most popular key–value databases. Most often, Redis is used for session caching, page cache, message queue.

In essence, this database is best for cache as it allows you to set up how long it should store the data and which data to wipe first. Redis is also known to be fast and high performing, which makes it perfect for cache tasks.

Before you connect to a Redis database, make sure you have Redis and Go installed on your Mac first. You can use Docker image of Redis instead of having Redis directly on your machine, if you want.

You will also need to install go-redis, a Redis client for Go. 

Begin by initializing Go module with this command:

go mod init github.com/my/repo

Next, install go-redis, one of the two most popular packages to interact with Redis in Golang:

go get github.com/go-redis/redis/v8

Connecting to a Redis database

Begin by making sure your Docker Redis container is running:

Redis database

If not, run the Redis Docker container:

docker run -d -p 6379:6379 redislabs/redismod

Now, we can incorporate our code to install go-redis from the previous step into our process:

go get github.com/go-redis/redis/v8

Before our final step, we need to create main.go file with our actual program. We used the following code:

package main
import (
    "fmt"
    "github.com/go-redis/redis"
)
func main() {
    fmt.Println("We are testing Go-Redis")
    client := redis.NewClient(&redis.Options{
        Addr: "localhost:6379",
        Password: "",
        DB: 0,
    })
    pong, err := client.Ping().Result()
    fmt.Println(pong, err)
}

To write our Go program, we used CodeRunner, an app for lightning-fast coding in more than 25 languages, including Go.

Coderunner for developers

You can either use CodeRunner or another editor app.

Change your directory in Terminal with cd command to be in the same folder as your main.go file from the previous step, and then get Go to run the file to establish the connection with the go run main.go command.

You should get a PONG response if the connection is successful:

PONG response

Interacting with Redis databases

The basics of interacting with a Redis database revolve around set and get commands.

Here’s the code for setting a value in a Redis database:

err = client.Set("name", "Billie", 0).Err()
if err != nil {
    fmt.Println(err)
}

To be sure you are doing everything right, you can also incorporate the get code into your program and get the value you’ve just added printed back to you.

Here’s the full code we used for that action in our Go program:

package main
import (
    "fmt"
    "github.com/go-redis/redis"
)
func main() {
    fmt.Println("We are testing Go-Redis")
    client := redis.NewClient(&redis.Options{
        Addr: "localhost:6379",
        Password: "",
        DB: 0,
    })
    pong, err := client.Ping().Result()
    fmt.Println(pong, err)
if err != nil {return}
    err = client.Set("name", "Billie", 0).Err()
if err != nil {
            fmt.Println(err)
        return
    }
val, err := client.Get("name").Result()
            if err != nil {
                fmt.Println(err)
            }
            
            fmt.Println(val)
}

To save your code snippets for later, you can use SnippetsLab, an app designed specifically for the task. You can keep your code bits there for easy access whenever you need them:

code snoppets

You can also save them as plain text files, but we prefer SnippetsLab to be able to better structure our snippets.

Also make sure you store code examples, since sometimes when you alter them, it’s possible to unintentionally incorporate a bug — and it’s good to have an original reference that worked before you tweaked it.

Setting expiration time for Redis DB values

One of the most valuable features of Redis in-memory database is that it allows you to store your values with an expiration date. In our examples above, we used 0 to avoid setting the duration for storing our set value, but what happens when we do?

Here’s the corresponding code line for that:

err = client.Set("name", "Tom", time.Second*5).Err()

How can we check that the value indeed expires in our set timeframe? There are a few ways to do that, but with our example, the easiest way to check is with this line of code:

time.Sleep(time.Second*6)

It allows us to ask our program to wait a certain amount of time before getting our set value. If we set the time at under 5 seconds, we get Tom back. But when the time is more than that, we get nothing back:

package main
import (
    "fmt"
    "github.com/go-redis/redis"
    "time"
)
func main() {
    fmt.Println("We are testing Go-Redis")
    client := redis.NewClient(&redis.Options{
        Addr: "localhost:6379",
        Password: "",
        DB: 0,
    })
    pong, err := client.Ping().Result()
    fmt.Println(pong, err)
if err != nil {return}
        
    err = client.Set("name", "Tom", time.Second*5).Err()
if err != nil {
            fmt.Println(err)
        return
    }
    time.Sleep(time.Second*4)
val, err := client.Get("name").Result()
            if err != nil {
                fmt.Println(err)
            }
            fmt.Println(val)
}

expiration time

Here we ran our main.go file with expiration time set at 4 seconds first and then switched it to 6. So in response to our first run of main.go, we got the name we set — Tom — back to us, but the second time we ran it, we got just the nil.

Using JSON with Redis

To store composite values, we can use JSON in our code:

package main
import (
        "fmt"
        "encoding/json"
        "github.com/go-redis/redis"
)
type Author struct {
    Name string `json:"name"`
    Age int `json:"age"`
}
func main() {
    client := redis.NewClient(&redis.Options{
        Addr: "localhost:6379",
        Password: "",
        DB: 0,
    })
    
    json, err := json.Marshal(Author{Name: "Ben", Age: 85})
    if err != nil {
        fmt.Println(err)
    }
    err = client.Set("id4", json, 0).Err()
    if err != nil {
        fmt.Println(err)
    }
    val, err := client.Get("id4").Result()
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(val)
}

With this code, we were able to store a composite value of a name and an age in our Redis database:

composite values

Final thoughts

As you can see, working with Redis in Go is very easy — all you need is establish the connection and begin setting your values.

Redis databases are great for storing information with an expiration date, which is one of the main reasons one of its main uses is for cache and storing messages. You can incorporate multiple Redis databases in your projects, as needed.

In the guide above, you’ve learnt how to set expiration time for your values and check that they are working, as well as about using JSON with your Redis databases.

The apps we’ve used throughout our tutorial — CodeRunner and SnippetsLab — are available on Setapp, a service with a curated collection of productivity tools for your Mac and iOS devices.

Browse Setapp’s carefully put-together collections of themed apps for a variety of everyday tasks on Mac or iPhone, pick the tools you’d like to use, and try them out all under a single subscription. Keep the most used ones on your devices all the time and get the ones you only need occasionally whenever you have a task on hand to tackle.

Try Setapp with our free 7-day trial now and explore all the tools available in our selection!

250+ apps for $9.99
per month

Sign up to Setapp and try them for free.

Security-tested