将 Azure Cache for Redis 连接到 Azure Spring Apps 中的应用程序

注意

基本计划和标准计划于 2025 年 3 月 17 日进入退休期。 有关详细信息,请参阅 Azure Spring Apps 停用公告

可以通过 Azure Spring Apps 将所选 Azure 服务自动连接到应用程序,而不必手动配置 Spring Boot 应用程序。 本文介绍如何将应用程序连接到 Azure Redis 缓存。

先决条件

  • 部署的 Azure Spring Apps 实例
  • Azure Redis 缓存服务实例
  • 用于 Azure CLI 的 Azure Spring Apps 扩展

如果没有已部署的 Azure Spring Apps 实例,请按照快速入门:将第一个应用程序部署到 Azure Spring Apps 中的步骤操作。

准备项目

  1. 在项目的 pom.xml 文件中,添加以下依赖项:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis-reactive</artifactId>
    </dependency>
    
  2. 从 application.properties 文件中,删除所有 spring.redis.* 属性

  3. 使用 az spring app update 更新当前部署,或者使用 az spring app deployment create 创建新的部署。

将应用连接到 Azure Cache for Redis

以下 Terraform 脚本演示如何使用 Azure Cache for Redis 设置 Azure Spring Apps 应用。

provider "azurerm" {
  features {}
}

variable "application_name" {
  type        = string
  description = "The name of your application"
  default     = "demo-abc"
}

resource "azurerm_resource_group" "example" {
  name     = "example-resources"
  location = "China North 2"
}

resource "azurerm_redis_cache" "redis" {
  name                = "redis-${var.application_name}-001"
  resource_group_name = azurerm_resource_group.example.name
  location            = azurerm_resource_group.example.location
  capacity            = 0
  family              = "C"
  sku_name            = "Standard"
  enable_non_ssl_port = false
  minimum_tls_version = "1.2"
}

resource "azurerm_spring_cloud_service" "example" {
  name                = "${var.application_name}"
  resource_group_name = azurerm_resource_group.example.name
  location            = azurerm_resource_group.example.location
}

resource "azurerm_spring_cloud_app" "example" {
  name                = "${var.application_name}-app"
  resource_group_name = azurerm_resource_group.example.name
  service_name        = azurerm_spring_cloud_service.example.name
  is_public           = true
  https_only          = true
}

resource "azurerm_spring_cloud_java_deployment" "example" {
  name                = "default"
  spring_cloud_app_id = azurerm_spring_cloud_app.example.id
  quota {
    cpu    = "2"
    memory = "4Gi"
  }
  instance_count      = 2
  jvm_options         = "-XX:+PrintGC"
  runtime_version     = "Java_11"

  environment_variables = {
    "spring.redis.host"     = azurerm_redis_cache.redis.hostname
    "spring.redis.password" = azurerm_redis_cache.redis.primary_access_key
    "spring.redis.port"     = "6380"
    "spring.redis.ssl"      = "true"
  }
}

resource "azurerm_spring_cloud_active_deployment" "example" {
  spring_cloud_app_id = azurerm_spring_cloud_app.example.id
  deployment_name     = azurerm_spring_cloud_java_deployment.example.name
}

后续步骤

本文介绍了如何将 Azure Spring Apps 中的应用程序连接到 Azure Cache for Redis。 若要详细了解如何将服务连接到应用程序,请参阅连接到 Azure Database for MySQL 实例