Quickstart: Use Azure Cache for Redis with Go

In this article, you learn how to build a REST API in Go that stores and retrieves user information backed by a HASH data structure in Azure Cache for Redis.

Skip to the code on GitHub

If you want to skip straight to the code, see the Go quickstart on GitHub.

Prerequisites

Create an Azure Cache for Redis instance

  1. To create a cache, sign in to the Azure portal and select Create a resource.

    Create a resource is highlighted in the left navigation pane.

  2. On the New page, select Databases and then select Azure Cache for Redis.

    On New, Databases is highlighted, and Azure Cache for Redis is highlighted.

  3. On the New Redis Cache page, configure the settings for your new cache.

    Setting Suggested value Description
    DNS name Enter a globally unique name. The cache name must be a string between 1 and 63 characters that contains only numbers, letters, or hyphens. The name must start and end with a number or letter, and can't contain consecutive hyphens. Your cache instance's host name will be <DNS name>.redis.cache.windows.net.
    Subscription Drop down and select your subscription. The subscription under which to create this new Azure Cache for Redis instance.
    Resource group Drop down and select a resource group, or select Create new and enter a new resource group name. Name for the resource group in which to create your cache and other resources. By putting all your app resources in one resource group, you can easily manage or delete them together.
    Location Drop down and select a location. Select a region near other services that will use your cache.
    Pricing tier Drop down and select a Pricing tier. The pricing tier determines the size, performance, and features that are available for the cache. For more information, see Azure Cache for Redis Overview.
  4. Select the Networking tab or click the Networking button at the bottom of the page.

  5. In the Networking tab, select your connectivity method.

  6. Select the Next: Advanced tab or click the Next: Advanced button on the bottom of the page.

  7. In the Advanced tab for a basic or standard cache instance, select the enable toggle if you want to enable a non-TLS port. You can also select which Redis version you would like use, either 4 or (PREVIEW) 6.

    Redis version 4 or 6.

  8. In the Advanced tab for premium cache instance, configure the settings for non-TLS port, clustering, and data persistence. You can also select which Redis version you would like use, either 4 or (PREVIEW) 6.

  9. Select the Next: Tags tab or click the Next: Tags button at the bottom of the page.

  10. Optionally, in the Tags tab, enter the name and value if you wish to categorize the resource.

  11. Select Review + create. You're taken to the Review + create tab where Azure validates your configuration.

  12. After the green Validation passed message appears, select Create.

It takes a while for the cache to create. You can monitor progress on the Azure Cache for Redis Overview page. When Status shows as Running, the cache is ready to use.

Retrieve host name, ports, and access keys from the Azure portal

To connect to an Azure Cache for Redis instance, cache clients need the host name, ports, and a key for the cache. Some clients might refer to these items by slightly different names. You can get the host name, ports, and keys from the Azure portal.

  • To get the access keys, from your cache left navigation, select Access keys.

    Azure Cache for Redis keys

  • To get the host name and ports, from your cache left navigation, select Properties. The host name is of the form <DNS name>.redis.cache.windows.net.

    Azure Cache for Redis properties

Review the code (Optional)

If you're interested in learning how the code works, you can review the following snippets. Otherwise, feel free to skip ahead to Run the application.

The open source go-redis library is used to interact with Azure Cache for Redis.

The main function starts off by reading the host name and password (Access Key) for the Azure Cache for Redis instance.

func main() {
    redisHost := os.Getenv("REDIS_HOST")
    redisPassword := os.Getenv("REDIS_PASSWORD")
...

Then, we establish connection with Azure Cache for Redis. We use tls.Config--Azure Cache for Redis only accepts secure connections with TLS 1.2 as the minimum required version.

...
op := &redis.Options{Addr: redisHost, Password: redisPassword, TLSConfig: &tls.Config{MinVersion: tls.VersionTLS12}}
client := redis.NewClient(op)

ctx := context.Background()
err := client.Ping(ctx).Err()
if err != nil {
    log.Fatalf("failed to connect with redis instance at %s - %v", redisHost, err)
}
...

If the connection is successful, HTTP handlers are configured to handle POST and GET operations and the HTTP server is started.

Note

gorilla mux library is used for routing (although it's not strictly necessary and we could have gotten away by using the standard library for this sample application).

uh := userHandler{client: client}

router := mux.NewRouter()
router.HandleFunc("/users/", uh.createUser).Methods(http.MethodPost)
router.HandleFunc("/users/{userid}", uh.getUser).Methods(http.MethodGet)

log.Fatal(http.ListenAndServe(":8080", router))

userHandler struct encapsulates a redis.Client, which is used by the createUser, getUser methods - code for these methods isn't included for brevity.

  • createUser: accepts a JSON payload (containing user information) and saves it as a HASH in Azure Cache for Redis.
  • getUser: fetches user info from HASH or returns an HTTP 404 response if not found.
type userHandler struct {
    client *redis.Client
}
...

func (uh userHandler) createUser(rw http.ResponseWriter, r *http.Request) {
    // details omitted
}
...

func (uh userHandler) getUser(rw http.ResponseWriter, r *http.Request) {
    // details omitted
}

Clone the sample application

Start by cloning the application from GitHub.

  1. Open a command prompt and create a new folder named git-samples.

    md "C:\git-samples"
    
  2. Open a git terminal window, such as git bash. Use the cd command to change to the new folder where you want to clone the sample app.

    cd "C:\git-samples"
    
  3. Run the following command to clone the sample repository. This command creates a copy of the sample app on your computer.

    git clone https://github.com/Azure-Samples/azure-redis-cache-go-quickstart.git
    

Run the application

The application accepts connectivity and credentials in the form of environment variables.

  1. Fetch the Host name and Access Keys (available via Access Keys) for Azure Cache for Redis instance in the Azure portal

  2. Set them to the respective environment variables:

    set REDIS_HOST=<Host name>:<port> (e.g. <name of cache>.redis.cache.windows.net:6380)
    set REDIS_PASSWORD=<Primary Access Key>
    
  3. In the terminal window, change to the correct folder. For example:

    cd "C:\git-samples\azure-redis-cache-go-quickstart"
    
  4. In the terminal, run the following command to start the application.

    go run main.go
    

The HTTP server will start on port 8080.

Test the application

  1. Create a few user entries. The below example uses curl:

    curl -i -X POST -d '{"id":"1","name":"foo1", "email":"foo1@baz.com"}' localhost:8080/users/
    curl -i -X POST -d '{"id":"2","name":"foo2", "email":"foo2@baz.com"}' localhost:8080/users/
    curl -i -X POST -d '{"id":"3","name":"foo3", "email":"foo3@baz.com"}' localhost:8080/users/
    
  2. Fetch an existing user with its id:

    curl -i localhost:8080/users/1
    

    You should get JSON response as such:

    {
        "email": "foo1@bar",
        "id": "1",
        "name": "foo1"
    }
    
  3. If you try to fetch a user who doesn't exist, you get an HTTP 404. For example:

    curl -i localhost:8080/users/100
    
    #response
    
    HTTP/1.1 404 Not Found
    Date: Fri, 08 Jan 2021 13:43:39 GMT
    Content-Length: 0
    

Clean up resources

If you're finished with the Azure resource group and resources you created in this quickstart, you can delete them to avoid charges.

Important

Deleting a resource group is irreversible, and the resource group and all the resources in it are permanently deleted. If you created your Azure Cache for Redis instance in an existing resource group that you want to keep, you can delete just the cache by selecting Delete from the cache Overview page.

To delete the resource group and its Redis Cache for Azure instance:

  1. From the Azure portal, search for and select Resource groups.

  2. In the Filter by name text box, enter the name of the resource group that contains your cache instance, and then select it from the search results.

  3. On your resource group page, select Delete resource group.

  4. Type the resource group name, and then select Delete.

    Delete your resource group for Azure Cache for Redis

Next steps

In this quickstart, you learned how to get started using Go with Azure Cache for Redis. You configured and ran a simple REST API-based application to create and get user information backed by a Redis HASH data structure.