Caching Application Data Using Redis Labs Redis

You can use Redis Labs Redis Cloud to cache application data. Redis Cloud is a fully-managed service offering a variety of options for running Redis.

Pricing

Redis Labs offers a free tier that provides 30mb of storage.

Setting up

To use Redis Labs Redis Cloud:

  1. Sign up for a Redis Labs account.
  2. Create a Redis Database using Redis Cloud. Be sure to specify GCE/us-central1 as the Cloud for the lowest latency. Specify a strong password as your Redis instance will be publicly accessible.
  3. Note the Endpoint for the database.

Installing a Redis client library

We recommend using Redigo.

Create a Go app for the flexible environment in the usual way.

Install the bindings.

go get -u https://github.com/garyburd/redigo

Connecting to Redis Labs Redis

Configure environment variables in your app.yaml with the endpoint and password for your Redis Labs Redis database:
env_variables:
  REDIS_ADDR: "<REDIS_HOST>:<REDIS_PORT>"
  REDIS_PASSSWORD: ""
Use the environment variables in your application code to configure a Redis client:
package main

import (
	"fmt"
	"net/http"
	"os"

	"github.com/garyburd/redigo/redis"

	"google.golang.org/appengine"
)

var redisPool *redis.Pool

func main() {
	redisAddr := os.Getenv("REDIS_ADDR")
	redisPassword := os.Getenv("REDIS_PASSWORD")

	redisPool = &redis.Pool{
		Dial: func() (redis.Conn, error) {
			conn, err := redis.Dial("tcp", redisAddr)
			if redisPassword == "" {
				return conn, err
			}
			if err != nil {
				return nil, err
			}
			if _, err := conn.Do("AUTH", redisPassword); err != nil {
				conn.Close()
				return nil, err
			}
			return conn, nil
		},
		// TODO: Tune other settings, like IdleTimeout, MaxActive, MaxIdle, TestOnBorrow.
	}

	http.HandleFunc("/", handle)
	appengine.Main()
}

func handle(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path != "/" {
		http.NotFound(w, r)
		return
	}

	redisConn := redisPool.Get()
	defer redisConn.Close()

	count, err := redisConn.Do("INCR", "count")
	if err != nil {
		msg := fmt.Sprintf("Could not increment count: %v", err)
		http.Error(w, msg, http.StatusInternalServerError)
		return
	}

	fmt.Fprintf(w, "Count: %d", count)
}

Testing Redis locally

If you are testing your app locally, you can still connect to your the Redis Labs Redis database. However, you might want to run a local instance of Redis to avoid interacting with production data.

Follow the directions in the Redis documentation to install and run Redis locally. Note that it currently isn't possible to run Redis locally on Windows.

Send feedback about...

App Engine flexible environment for Go