Use Azure Redis Cache in Spring

Azure Cache for Redis provides an in-memory data store based on the Redis software. Redis improves the performance and scalability of an application that uses backend data stores heavily.

This tutorial demonstrates how to use a Redis cache to store and retrieve data in a Spring Boot application.

In this tutorial, we include two authentication methods: Microsoft Entra authentication and Redis authentication. The Passwordless tab shows the Microsoft Entra authentication and the Password tab shows the Redis authentication.

Microsoft Entra authentication is a mechanism for connecting to Azure Cache for Redis using identities defined in Microsoft Entra ID. With Microsoft Entra authentication, you can manage database user identities and other Microsoft services in a central location, which simplifies permission management.

Redis authentication uses passwords in Redis. If you choose to use passwords as credentials, you need to manage the passwords by yourself.

Prerequisites

Caching Data to Azure Cache for Redis

With an Azure Cache for Redis instance, you can cache data using Spring Cloud Azure.

To install the Spring Cloud Azure Starter Data Redis with Lettuce module, add the following dependencies to your pom.xml file:

<dependencies>
 <dependency>
   <groupId>com.azure.spring</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
 </dependency>
 <dependency>
   <groupId>com.azure.spring</groupId>
   <artifactId>spring-cloud-azure-starter-data-redis-lettuce</artifactId>
 </dependency>
 <dependency>
   <groupId>com.azure.spring</groupId>
   <artifactId>spring-boot-starter-data-redis</artifactId>
 </dependency>
</dependencies>

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>com.azure.spring</groupId>
      <artifactId>spring-cloud-azure-dependencies</artifactId>
      <version>5.19.0</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

Note

This Bill of Material (BOM) should be configured in the <dependencyManagement> section of your pom.xml file. This configuration ensures that all Spring Cloud Azure dependencies are using the same version. For more information about the version used for this BOM, see Which Version of Spring Cloud Azure Should I Use.

Code the application

To use a Redis cache to store and retrieve data, configure the application by using the following steps:

  1. Configure Redis cache credentials in the application.properties configuration file, as shown in the following example.

    spring.data.redis.host=<your-redis-name>.redis.cache.windows.net
    spring.data.redis.port=6380
    spring.data.redis.username=<your-redis-username>
    spring.data.redis.ssl.enabled=true
    spring.data.redis.azure.passwordless-enabled=true
    

    Note

    To get the value for username, follow the instructions in the Enable Microsoft Entra ID authentication on your cache section of Use Microsoft Entra ID for cache authentication, and copy the username value.

  2. Edit the startup class file to show the following content. This code stores and retrieves data.

    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.CommandLineRunner;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.data.redis.core.StringRedisTemplate;
    import org.springframework.data.redis.core.ValueOperations;
    
    @SpringBootApplication
    public class DemoCacheApplication implements CommandLineRunner {
    
        private static final Logger LOGGER = LoggerFactory.getLogger(DemoCacheApplication.class);
    
        @Autowired
        private StringRedisTemplate template;
    
        public static void main(String[] args) {
            SpringApplication.run(DemoCacheApplication.class, args);
        }
    
        @Override
        public void run(String... args) {
            ValueOperations<String, String> ops = this.template.opsForValue();
            String key = "testkey";
            if(!this.template.hasKey(key)){
                ops.set(key, "Hello World");
                LOGGER.info("Add a key is done");
            }
            LOGGER.info("Return the value from the cache: {}", ops.get(key));
        }
    
    }
    

Then, start the application. The application retrieves data from your Redis cache. You should see logs similar to the following example:

Add a key is done
Return the value from the cache: Hello World

Deploy to Azure Spring Apps

Now that you have the Spring Boot application running locally, it's time to move it to production. Azure Spring Apps makes it easy to deploy Spring Boot applications to Azure without any code changes. The service manages the infrastructure of Spring applications so developers can focus on their code. Azure Spring Apps provides lifecycle management using comprehensive monitoring and diagnostics, configuration management, service discovery, CI/CD integration, blue-green deployments, and more. To deploy your application to Azure Spring Apps, see Deploy your first application to Azure Spring Apps.

Next steps

To learn more about Spring and Azure, continue to the Spring on Azure documentation center.