在 Spring 中使用 Azure Redis 缓存
Azure Cache for Redis 提供基于 Redis 软件的内存中数据存储。 Redis 可提高使用后端数据存储的应用程序的性能和可伸缩性。
本教程演示如何使用 Redis 缓存在 Spring Boot 应用程序中存储和检索数据。
先决条件
Azure 订阅 - 免费创建订阅。
Java 开发工具包 (JDK) 版本 8 或更高版本。
Apache Maven 版本 3.0 或更高版本。
用来测试功能的 cURL 或类似的 HTTP 实用工具。
Redis 缓存实例。 如果没有,请参阅 快速入门:创建开源 Redis 缓存。
Spring Boot 应用程序。 如果没有,请使用 Spring Initializr 创建一个 Maven 项目。 请务必选择 Maven 项目,并在“依赖项”下添加 Spring Web 和 Spring Data 反应 Redis 依赖项,然后选择 Java 版本 8 或更高版本。
编写应用程序代码
若要使用 Redis 缓存来存储和检索数据,请使用以下步骤配置应用程序。
在 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 缓存。
编辑启动类文件以显示以下内容。 此代码存储并检索数据。
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)); } }
启动应用程序。 应用程序将从 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”文档中心。
反馈
https://aka.ms/ContentUserFeedback。
即将发布:在整个 2024 年,我们将逐步淘汰作为内容反馈机制的“GitHub 问题”,并将其取代为新的反馈系统。 有关详细信息,请参阅:提交和查看相关反馈