How to Use Redis in Golang

How to Use Redis in Golang

Many developers use Redis to cache data because it stores data in memory. It enables us to reduce load to our database or external service. Data stored in Redis have an expiration time, so Redis can release memory that is no longer used. This article will show you the basics of integrating Redis with Golang.

There are many client libraries to use Redis in Golang. We will use https://github.com/gomodule/redigo in this article. It is one of the recommended client libraries. You can visit https://redis.io/clients#go for more client libraries.

Create Connection Pool

For a service with high traffic, it is recommended to use a connection pool to access Redis. Whenever we want to access the Redis, we get one connection from the pool. Then put it back to the pool, so that the connection can be reused. It is also thread-safe. We can check the connection before it is put back to the pool using TestOnBorrow function. If the test returns an error, the connection will be closed.
To create a new connection pool:

	import (
		"github.com/gomodule/redigo/redis"
	)

	// ...

	pool = &redis.Pool{
		MaxIdle:     5,
		IdleTimeout: 60 * time.Second,
		Dial:        func() (redis.Conn, error) { return redis.Dial("tcp", "localhost:6379") },
		TestOnBorrow: func(c redis.Conn, t time.Time) error {
			if time.Since(t) < time.Minute {
				return nil
			}
			_, err := c.Do("PING")
			return err
		},
	}

To read or write data, we get one connection from the pool, use the connection then return it to the pool. We use Do function of a connection to execute commands.

Set Value to Redis

The most simple data type in Redis is a key-value format. A string value is stored in Redis with a key identifier. The expiration time is optional, but it is recommended to always set the expiration time to your data. We execute command SET to set the value. To use it in Go:

	conn := pool.Get()
	defer conn.Close()

	reply, err := redis.String(conn.Do("SET", key, value, "EX", expireInSeconds))
    // reply is `OK` if success
    // 
    ...

First, we get a connection with pool.Get() and defer conn.Close() to make sure the connection is returned after to the pool. Then we use the connection to execute SET command to set a value to the key with expiration time. The expiration time is in seconds. redis.String is a helper function to convert the command result to a string. We will get OK as a reply if the set is successful.

Get Value from Redis

The steps to get a value from Redis is similar to Set. To get the data, we use command GET. Below is a sample of Go code.

	conn := pool.Get()
	defer conn.Close()

	reply, err := redis.String(conn.Do("GET", key))
	// you will get the data in reply
    ...

You will get the value of the key in reply. To get the time to live associated with the key you can use TTL command.

Conclusion

One of the usages of Redis is to cache resources. Redis was chosen because it is fast. You can cache database resources or external resources that need API calls. This article only shows you the most basic usage usages of Redis in Go. But we can make a very useful caching with these basic functions. There are many more features of Redis than just set and get key-value data. You can store Lists, Hashes, or even Geolocations.

go  redis 

See also

comments powered by Disqus