Edit

Share via


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. In the Azure portal, search for and select Azure Cache for Redis.

  2. On the Azure Cache for Redis page, select Create > Azure Cache for Redis.

  3. On the Basics tab of the New Redis Cache page, configure the following settings:

    • Subscription: Select the subscription to use.
    • Resource group: Select a resource group, or select Create new and enter a new resource group name. Putting all your app resources in the same resource group lets you easily manage or delete them together.
    • Name: Enter a cache name that's unique in the region. The name must:
      • Be a string of 1 to 63 characters.
      • Contain only numbers, letters, and hyphens.
      • Start and end with a number or letter.
      • Not contain consecutive hyphens.
    • Region: Select an Azure region near other services that use your cache.
    • Cache SKU: Select a SKU to determine the available sizes, performance, and features for your cache.
    • Cache size: Select a cache size. For more information, see Azure Cache for Redis overview.

    Screenshot that shows the Basics tab of the New Redis Cache page.

  4. Select the Networking tab, or select Next: Networking.

  5. On the Networking tab, select a connectivity method to use for the cache. Private Endpoint is recommended for security. If you select Private Endpoint, select Add private endpoint and create the private endpoint.

  6. Select the Advanced tab, or select Next: Advanced.

  7. On the Advanced pane, configure the following options:

    • Select Microsoft Entra Authentication or Access Keys Authentication. Microsoft Entra Authentication is enabled by default.
    • Choose whether to Enable the non-TLS port.
    • For a Premium cache, you can configure or disable Availability zones. You can't disable availability zones after the cache is created. For a Standard cache, availability zones are allocated automatically. Availability zones aren't available for Basic SKU.
    • For a Premium cache, configure the settings for Replica count, Clustering and Shard count, System-assigned managed identity, and Data persistence.

    The following image shows the Advanced tab for the Standard SKU.

    Screenshot showing the Advanced pane for a Standard SKU cache.

    Important

    Use Microsoft Entra ID with managed identities to authorize requests against your cache if possible. Authorization using Microsoft Entra ID and managed identity provides better security and is easier to use than shared access key authorization. For more information about using managed identities with your cache, see Use Microsoft Entra ID for cache authentication.

  8. Optionally, select the Tags tab or select Next: Tags, and enter tag names and values to categorize your cache resources.

  9. Select Review + create, and once validation passes, select Create.

The new cache deployment takes several minutes. You can monitor deployment progress on the portal Azure Cache for Redis page. When the cache Status displays Running, the cache is ready to use.

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

To connect your Azure Cache for Redis server, the cache client needs 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 host name and ports for your cache, select Overview from the Resource menu. The host name is of the form <DNS name>.redis.cache.windows.net.

    Screenshot showing Azure Cache for Redis properties.

  • To get the access keys, select Authentication from the Resource menu. Then, select the Access keys tab.

    Screenshot showing Azure Cache for Redis access keys.

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]/azure-cache-for-redis/cache-remove-tls-10-11.md).

...
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 want to continue to use the resources you created in this article, keep the resource group.

Otherwise, if you're finished with the resources, you can delete the Azure resource group that you created to avoid charges.

Important

Deleting a resource group is irreversible. When you delete a resource group, all the resources in it are permanently deleted. Make sure that you do not accidentally delete the wrong resource group or resources. If you created the resources inside an existing resource group that contains resources you want to keep, you can delete each resource individually instead of deleting the resource group.

To delete a resource group

  1. Sign in to the Azure portal, and then select Resource groups.

  2. Select the resource group you want to delete.

    If there are many resource groups, use the Filter for any field... box, type the name of your resource group you created for this article. Select the resource group in the results list.

    Screenshot showing a list of resource groups to delete in the working pane.

  3. Select Delete resource group.

  4. You're asked to confirm the deletion of the resource group. Type the name of your resource group to confirm, and then select Delete.

    Screenshot showing a form that requires the resource name to confirm deletion.

After a few moments, the resource group and all of its resources are deleted.

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.