你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

将 Azure Database for MySQL 实例连接到 Azure Spring Apps 中的应用程序

注意

从 2025 年 3 月中旬开始,基本标准企业计划将被弃用,停用期为 3 年。 建议过渡到 Azure 容器应用。 有关详细信息,请参阅 Azure Spring Apps 停用公告

从 2024 年 9 月 30 日开始,标准消耗和专用计划将被弃用,六个月后将完全关闭。 建议过渡到 Azure 容器应用。 有关详细信息,请参阅将 Azure Spring Apps 标准消耗和专用计划迁移到 Azure 容器应用

本文适用于:✔️ Java ✔️ C#

本文适用于:✔️ 基本版/标准版 ✔️ 企业版

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

先决条件

准备项目

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

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>com.azure.spring</groupId>
        <artifactId>spring-cloud-azure-starter-jdbc-mysql</artifactId>
    </dependency>
    
  2. 在 application.properties 文件中,删除所有 spring.datasource.* 属性。

  3. 通过运行 az spring app deploy 更新当前应用,或者通过运行 az spring app deployment create 针对此更改创建新的部署。

将应用连接到 Azure Database for MySQL 实例

注意

默认情况下,服务连接器在应用程序级别创建。 若要替代连接,可以在部署中再次创建其他连接。

按照这些步骤,将 Spring 应用配置为使用系统分配的托管标识连接到 Azure Database for MySQL 灵活服务器。

  1. 使用以下命令,为 Azure CLI 安装服务连接器无密码扩展。

    az extension add --name serviceconnector-passwordless --upgrade
    
  2. 然后,使用以下命令为 Microsoft Entra 身份验证创建用户分配的托管标识。 请务必将示例中的变量替换为实际值。 有关详细信息,请参阅设置 Azure Database for MySQL 灵活服务器的 Microsoft Entra 身份验证

    export AZ_IDENTITY_RESOURCE_ID=$(az identity create \
        --name $AZURE_USER_IDENTITY_NAME \
        --resource-group $AZURE_IDENTITY_RESOURCE_GROUP \
        --query id \
        --output tsv)
    
  3. 运行 az spring connection create 命令,如以下示例所示。 请务必将示例中的变量替换为实际值。

    az spring connection create mysql-flexible \
        --resource-group $AZURE_SPRING_APPS_RESOURCE_GROUP \
        --service $AZURE_SPRING_APPS_SERVICE_INSTANCE_NAME \
        --app $APP_NAME \
        --target-resource-group $MYSQL_RESOURCE_GROUP \
        --server $MYSQL_SERVER_NAME \
        --database $DATABASE_NAME \
        --system-identity mysql-identity-id=$AZ_IDENTITY_RESOURCE_ID
    

后续步骤

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