在 Spring 中使用 Azure Redis 缓存

Azure Cache for Redis 提供基于 Redis 软件的内存中数据存储。 Redis 可提高使用后端数据存储的应用程序的性能和可伸缩性。

本教程演示如何使用 Redis 缓存在 Spring Boot 应用程序中存储和检索数据。

先决条件

编写应用程序代码

若要使用 Redis 缓存来存储和检索数据,请使用以下步骤配置应用程序。

  1. application.properties 配置文件中配置 Redis 缓存凭据,如以下示例所示。

    # Specify the DNS URI of your Redis cache.
    spring.data.redis.host=<your-redis-name>.redis.cache.windows.net
    
    # Specify the port for your Redis cache.
    spring.data.redis.port=6379
    
    # Specify the access key for your Redis cache.
    spring.data.redis.password=<your-redis-access-key>
    

    注意

    如果使用其他启用了 SSL 的 Redis 客户端(如 Jedis),则需要在 application.properties 文件中指定要使用 SSL,并使用端口 6380。 例如:

    # Specify the DNS URI of your Redis cache.
    spring.data.redis.host=<your-redis-name>.redis.cache.windows.net
    # Specify the access key for your Redis cache.
    spring.data.redis.password=<your-redis-access-key>
    # Specify that you want to use SSL.
    spring.data.redis.ssl.enabled=true
    # Specify the SSL port for your Redis cache.
    spring.data.redis.port=6380
    

    有关详细信息,请参阅 快速入门:在 Java 中使用 Azure Redis 缓存。

  2. 编辑启动类文件以显示以下内容。 此代码存储并检索数据。

    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));
        }
    
    }
    
  3. 启动应用程序。 应用程序将从 Redis 缓存中检索数据。 你将看到类似于以下示例的日志:

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

部署到 Azure Spring Apps

现在,你已在本地运行 Spring Boot 应用程序,现在可以将其移动到生产环境。 使用 Azure Spring Apps 可以轻松地将 Spring Boot 应用程序部署到 Azure,而无需进行任何代码更改。 该服务管理 Spring 应用程序的基础结构,让开发人员可以专注于代码。 Azure Spring Apps 可以通过以下方法提供生命周期管理:综合性监视和诊断、配置管理、服务发现、CI/CD 集成、蓝绿部署等。 若要将应用程序部署到 Azure Spring Apps,请参阅将 第一个应用程序部署到 Azure Spring Apps

后续步骤

若要了解有关 Spring 和 Azure 的详细信息,请继续访问“Azure 上的 Spring”文档中心。