Basic Redis Examples with Go

POOL

To establish connectivity in redigo, you need to create a redis.Pool object which is a pool of connections to Redis. In order to do this, you can use something like the following:

func main() {    pool := newPool()
conn := pool.Get()
defer conn.Close()
err := ping(conn)
if err != nil {
fmt.Println(err)
}
...

PING

If you wish you to simply check connectivity, you can use Redis’ PING command.

SET

Use the Redis SET command to add a key:value pair to Redis. Below is a trivial example of adding a key (“Favorite Movie”) and a string value for it (“Repo Man”) as well as an int value (1984 as the movie Release Year). The blank identifier is used for the reply as we only need to check for errors (“OK” is the only thing that comes back on a successful SET command reply).

// set executes the redis SET command
func set(c redis.Conn) error {
_, err := c.Do("SET", "Favorite Movie", "Repo Man")
if err != nil {
return err
}
_, err = c.Do("SET", "Release Year", 1984)
if err != nil {
return err
}
return nil
}

GET

In order to retrieve a value for a given key, use the Redis GET command. Some simple examples are below, including an example where no results are retrieved. We can check for redis.ErrNil to determine if nothing is returned and should handle appropriately.

STRUCT (SET)

For my purposes of building a look-aside cache, I want to store objects in cache in their entirety in Redis. There seem to be a few different viewpoints on doing this — one where you store your object using a Redis Hash data type and the HMSET command. This is nice because, if need be you can update individual values within the object independently. I have seen examples of people using the redigo AddFlat method of the redigo.Args type to accomplish this, but also noted in redigo’s FAQ that redigo does not actually provide a way to serialize structs to Redis, so I stayed away from trying this.

STRUCT (GET)

The example below shows retrieving the object using the GET command and then deserializing it with json.Unmarshal

{Username:otto MobileID:1234567890 Email:ottoM@repoman.com FirstName:Otto LastName:Maddox}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Dan Gillis

Dan Gillis

Go enthusiast; Loyalty/CRM Technology Leader; Drummer; Vinyl geek; Husband/Dad