Quickstart: Use Azure Cache for Redis with a Go app
In this quickstart, 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
This article describes how to create an app by using the Azure portal and then modify the code to end up with a working sample app.
If you want to go straight to the code, see the Go quickstart sample on GitHub.
Prerequisites
- An Azure subscription. Create one for free
- Go (preferably version 1.13 or later)
- Git
- An HTTP client like curl
Create a cache
To create a cache, sign in to the Azure portal. On the portal menu, select Create a resource.
On the Get Started pane, enter Azure Cache for Redis in the search bar. In the search results, find Azure Cache for Redis, and then select Create.
On the New Redis Cache pane, on the Basics tab, configure the following settings for your cache:
Setting Action Description Subscription Select your Azure subscription. The subscription to use to create the new instance of Azure Cache for Redis. Resource group Select a resource group, or select Create new and enter a new resource group name. A 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. DNS name Enter a unique name. The cache name must be a string of 1 to 63 characters that contains only numbers, letters, and hyphens. The name must start and end with a number or letter, and it can't contain consecutive hyphens. Your cache instance's host name is \<DNS name>.redis.cache.windows.net
.Location Select a location. An Azure region that is near other services that use your cache. Cache SKU Select a SKU. The SKU determines the size, performance, and feature parameters that are available for the cache. For more information, see Azure Cache for Redis overview. Cache size Select a cache size. For more information, see Azure Cache for Redis overview. Select the Networking tab or select Next: Networking.
On the Networking tab, select a connectivity method to use for the cache.
Select the Advanced tab or select Next: Advanced.
On the Advanced pane, verify or select an authentication method based on the following information:
- By default, for a new Basic, Standard, or Premium cache, Microsoft Entra Authentication is enabled and Access Keys Authentication is disabled.
- For Basic or Standard caches, you can choose the selection for a non-TLS port.
- For Standard and Premium caches, you can choose to enable availability zones. You can't disable availability zones after the cache is created.
- For a Premium cache, configure the settings for non-TLS port, clustering, managed identity, and data persistence.
Important
For optimal security, we recommend that you use Microsoft Entra ID with managed identities to authorize requests against your cache if possible. Authorization by using Microsoft Entra ID and managed identities provides superior security and ease of use over shared access key authorization. For more information about using managed identities with your cache, see Use Microsoft Entra ID for cache authentication.
(Optional) Select the Tags tab or select Next: Tags.
(Optional) On the Tags tab, enter a tag name and value if you want to categorize your cache resource.
Select the Review + create button.
On the Review + create tab, Azure automatically validates your configuration.
After the green Validation passed message appears, select Create.
A new cache deployment occurs over several minutes. You can monitor the progress of the deployment on the Azure Cache for Redis Overview pane. When Status displays Running, the cache is ready to use.
Get the host name, ports, and access key
To connect to your Azure Cache for Redis server, the cache client needs the cache's host name, ports, and an access key. Some clients might refer to these items by using slightly different names. You can get the host name, ports, and keys in the Azure portal.
To get an access key for your cache:
- In the Azure portal, go to your cache.
- On the service menu, under Settings, select Authentication.
- On the Authentication pane, select the Access keys tab.
- To copy the value for an access key, select the Copy icon in the key field.
To get the host name and ports for your cache:
- In the Azure portal, go to your cache.
- On the service menu, select Overview.
- Under Essentials, for Host name, select the Copy icon to copy the host name value. The host name value has the form
<DNS name>.redis.cache.windows.net
. - For Ports, select the Copy icon to copy the port values.
Review the code (optional)
If you're interested in learning how the code works, you can review the following code snippets. 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 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, you establish connection with Azure Cache for Redis. We use tls.Config. Azure Cache for Redis supports only secure connections, and 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
The gorilla mux library is used for routing (although it's not required, and using the standard library for this sample application is an option).
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))
The userHandler
struct encapsulates redis.Client. The createUser
and getUser
methods use redis.Client. For brevity, the code for these methods isn't included in this article.
createUser
: Accepts a JSON payload (that has user information) and saves it as aHASH
in Azure Cache for Redis.getUser
: Fetches user info fromHASH
or returns an HTTP404
response if it's 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 on GitHub:
In the Command Prompt window for your computer's root directory, create a folder named git-samples:
md "C:\git-samples"
Open a git terminal window, such as by using Git Bash. Use the
cd
command to go to the new folder to clone the sample app.cd "C:\git-samples"
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.
In the Azure portal, get the host name and access key for the instance of Azure Cache for Redis.
Set the host name and access key to the following environment variables:
set REDIS_HOST=<Host name>:<port> (for example, <name of cache>.redis.cache.windows.net:6380) set REDIS_PASSWORD=<Primary Access Key>
In the terminal, go to the folder you created for the samples:
For example:
cd "C:\git-samples\azure-redis-cache-go-quickstart"
In the terminal, start the application by using this command:
go run main.go
The HTTP server starts on port 8080
.
Test the application
Create a few user entries.
The following 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/
Fetch an existing user by using the value for
id
:curl -i localhost:8080/users/1
The output is a JSON response that's similar to this example:
{ "email": "foo1@bar", "id": "1", "name": "foo1" }
If you try to fetch a user who doesn't exist, you get an HTTP
404
error message.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, to avoid charges related to the resources, if you're finished using the resources, you can delete the Azure resource group that you created.
Warning
Deleting a resource group is irreversible. When you delete a resource group, all the resources in the resource group 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 has resources you want to keep, you can delete each resource individually instead of deleting the resource group.
Delete a resource group
Sign in to the Azure portal, and then select Resource groups.
Select the resource group to delete.
If there are many resource groups, in Filter for any field, enter the name of the resource group you created to complete this article. In the list of search results, select the resource group.
Select Delete resource group.
In the Delete a resource group pane, enter the name of your resource group to confirm, and then select Delete.
Within a few moments, the resource group and all of its resources are deleted.