教程:使用 Linux 上的 Azure 应用服务和 Azure Cosmos DB 生成 Java Spring Boot Web 应用Tutorial: Build a Java Spring Boot web app with Azure App Service on Linux and Azure Cosmos DB

本教程将指导你完成在 Azure 上生成、配置、部署和缩放 Java Web 应用的过程。This tutorial walks you through the process of building, configuring, deploying, and scaling Java web apps on Azure. 完成本教程后,你将获得一个 Spring Boot 应用程序,该应用程序可在 Linux 上运行的 Azure 应用服务运行的 Azure Cosmos DB 中存储数据。When you are finished, you will have a Spring Boot application storing data in Azure Cosmos DB running on Azure App Service on Linux.

在 Azure Cosmos DB 中存储数据的 Spring Boot 应用程序

在本教程中,你将了解如何执行以下操作:In this tutorial, you learn how to:

  • 创建 Cosmos DB 数据库。Create a Cosmos DB database.
  • 将示例应用连接到数据库并在本地对其进行测试Connect a sample app to the database and test it locally
  • 将示例应用部署到 AzureDeploy the sample app to Azure
  • 从应用服务流式传输诊断日志Stream diagnostic logs from App Service
  • 添加更多实例以横向扩展示例应用Add additional instances to scale out the sample app

如果没有 Azure 订阅,可在开始前创建一个试用帐户If you don't have an Azure subscription, create a trial account before you begin.

先决条件Prerequisites

克隆示例 TODO 应用并准备存储库Clone the sample TODO app and prepare the repo

本教程使用一个示例 TODO 列表应用,该应用的 Web UI 可以调用 Spring Data Azure Cosmos DB 支持的 Spring REST API。This tutorial uses a sample TODO list app with a web UI that calls a Spring REST API backed by Spring Data Azure Cosmos DB. GitHub 上提供了该应用的代码。The code for the app is available on GitHub. 若要详细了解如何使用 Spring 和 Cosmos DB 编写 Java 应用,请参阅 Spring Boot Starter 与 Azure Cosmos DB SQL API 教程Spring Data Azure Cosmos DB 快速入门To learn more about writing Java apps using Spring and Cosmos DB, see the Spring Boot Starter with the Azure Cosmos DB SQL API tutorial and the Spring Data Azure Cosmos DB quick start.

在终端中运行以下命令,以克隆示例存储库并设置示例应用环境。Run the following commands in your terminal to clone the sample repo and set up the sample app environment.

git clone --recurse-submodules https://github.com/Azure-Samples/e2e-java-experience-in-app-service-linux-part-2.git
cd e2e-java-experience-in-app-service-linux-part-2
yes | cp -rf .prep/* .

创建 Azure Cosmos DBCreate an Azure Cosmos DB

遵循以下步骤在订阅中创建 Azure Cosmos DB 数据库。Follow these steps to create an Azure Cosmos DB database in your subscription. TODO 列表应用在运行时将连接到此数据库并存储自身的数据,不管你在哪个位置运行应用程序,它都会保存应用程序状态。The TODO list app will connect to this database and store its data when running, persisting the application state no matter where you run the application.

  1. 登录到 Azure CLI;(可选)如果有多个订阅连接到登录凭据,请设置订阅。Login your Azure CLI, and optionally set your subscription if you have more than one connected to your login credentials.

    az cloud set -n AzureChinaCloud
    az login
    az account set -s <your-subscription-id>
    
  2. 创建 Azure 资源组并记下资源组名称。Create an Azure Resource Group, noting the resource group name.

    az group create -n <your-azure-group-name> \
        -l <your-resource-group-region>
    
  3. 创建 GlobalDocumentDB 类型的 Azure Cosmos DB。Create Azure Cosmos DB with the GlobalDocumentDB kind. Cosmos DB 的名称只能使用小写字母。The name of Cosmos DB must use only lower case letters. 记下命令响应中的 documentEndpoint 字段。Note down the documentEndpoint field in the response from the command.

    az cosmosdb create --kind GlobalDocumentDB \
        -g <your-azure-group-name> \
        -n <your-azure-COSMOS-DB-name-in-lower-case-letters>
    
  4. 获取用于连接应用的 Azure Cosmos DB 密钥。Get your Azure Cosmos DB key to connect to the app. primaryMasterKeydocumentEndpoint 保存在方便的位置,因为在下一步骤中需要用到。Keep the primaryMasterKey, documentEndpoint nearby as you'll need them in the next step.

    az cosmosdb list-keys -g <your-azure-group-name> -n <your-azure-COSMOSDB-name>
    

配置 TODO 应用属性Configure the TODO app properties

在计算机上打开终端。Open a terminal on your computer. 复制所克隆的存储库中的示例脚本文件,以便可以根据刚刚创建的 Cosmos DB 数据库自定义该文件。Copy the sample script file in the cloned repo so you can customize it for your Cosmos DB database you just created.

cd initial/spring-todo-app
cp set-env-variables-template.sh .scripts/set-env-variables.sh

在偏好的编辑器中编辑 .scripts/set-env-variables.sh,并提供 Azure Cosmos DB 连接信息。Edit .scripts/set-env-variables.sh in your favorite editor and supply Azure Cosmos DB connection info. 对于应用服务 Linux 配置,请使用前面在创建 Cosmos DB 数据库时所用的相同区域 (your-resource-group-region) 和资源组 (your-azure-group-name)。For the App Service Linux configuration, use the same region as before (your-resource-group-region) and resource group (your-azure-group-name) used when creating the Cosmos DB database. 选择唯一的 WEBAPP_NAME,因为任何 Azure 部署中不能出现任何 Web 应用名称重复的情况。Choose a WEBAPP_NAME that is unique since it cannot duplicate any web app name in any Azure deployment.

export COSMOSDB_URI=<put-your-COSMOS-DB-documentEndpoint-URI-here>
export COSMOSDB_KEY=<put-your-COSMOS-DB-primaryMasterKey-here>
export COSMOSDB_DBNAME=<put-your-COSMOS-DB-name-here>

# App Service Linux Configuration
export RESOURCEGROUP_NAME=<put-your-resource-group-name-here>
export WEBAPP_NAME=<put-your-Webapp-name-here>
export REGION=<put-your-REGION-here>

然后运行脚本:Then run the script:

source .scripts/set-env-variables.sh

TODO 列表应用的 application.properties 中使用了这些环境变量。These environment variables are used in application.properties in the TODO list app. properties 文件中的字段为 Spring Data 设置默认的存储库配置:The fields in the properties file set up a default repository configuration for Spring Data:

azure.cosmosdb.uri=${COSMOSDB_URI}
azure.cosmosdb.key=${COSMOSDB_KEY}
azure.cosmosdb.database=${COSMOSDB_DBNAME}
@Repository
public interface TodoItemRepository extends DocumentDbRepository<TodoItem, String> {
}

然后,示例应用使用从 com.microsoft.azure.spring.data.cosmosdb.core.mapping.Document 导入的 @Document 注释,来设置 Cosmos DB 要存储和管理的实体类型:Then the sample app uses the @Document annotation imported from com.microsoft.azure.spring.data.cosmosdb.core.mapping.Document to set up an entity type to be stored and managed by Cosmos DB:

@Document
public class TodoItem {
    private String id;
    private String description;
    private String owner;
    private boolean finished;

运行示例应用Run the sample app

使用 Maven 运行示例。Use Maven to run the sample.

mvn package spring-boot:run

输出应如下所示。The output should look like the following.

bash-3.2$ mvn package spring-boot:run
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building spring-todo-app 2.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]


[INFO] SimpleUrlHandlerMapping - Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
[INFO] SimpleUrlHandlerMapping - Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
[INFO] WelcomePageHandlerMapping - Adding welcome page: class path resource [static/index.html]
2018-10-28 15:04:32.101  INFO 7673 --- [           main] c.m.azure.documentdb.DocumentClient      : Initializing DocumentClient with serviceEndpoint [https://sample-cosmos-db-chinaeast.documents.azure.cn:443/], ConnectionPolicy [ConnectionPolicy [requestTimeout=60, mediaRequestTimeout=300, connectionMode=Gateway, mediaReadMode=Buffered, maxPoolSize=800, idleConnectionTimeout=60, userAgentSuffix=;spring-data/2.0.6;098063be661ab767976bd5a2ec350e978faba99348207e8627375e8033277cb2, retryOptions=com.microsoft.azure.documentdb.RetryOptions@6b9fb84d, enableEndpointDiscovery=true, preferredLocations=null]], ConsistencyLevel [null]
[INFO] AnnotationMBeanExporter - Registering beans for JMX exposure on startup
[INFO] TomcatWebServer - Tomcat started on port(s): 8080 (http) with context path ''
[INFO] TodoApplication - Started TodoApplication in 45.573 seconds (JVM running for 76.534)

启动应用后,可在本地使用以下链接来访问 Spring TODO 应用:http://localhost:8080/You can access Spring TODO App locally using this link once the app is started: http://localhost:8080/.

本地访问 Spring TODO 应用

如果看到了异常而不是“已启动 TodoApplication”消息,请检查上一步骤所述的 bash 脚本是否正确导出了环境变量,并且是否为创建的 Azure Cosmos DB 数据库提供了正确的值。If you see exceptions instead of the "Started TodoApplication" message, check that the bash script in the previous step exported the environment variables properly and that the values are correct for the Azure Cosmos DB database you created.

配置 Azure 部署Configure Azure deployment

打开 initial/spring-boot-todo 目录中的 pom.xml 文件,并添加以下适用于 Maven 的 Azure Web 应用插件配置。Open the pom.xml file in the initial/spring-boot-todo directory and add the following Azure Web App Plugin for Maven configuration.

<plugins>

    <!--*************************************************-->
    <!-- Deploy to Java SE in App Service Linux           -->
    <!--*************************************************-->

    <plugin>
        <groupId>com.microsoft.azure</groupId>
        <artifactId>azure-webapp-maven-plugin</artifactId>
        <version>1.11.0</version>
        <configuration>
            <schemaVersion>v2</schemaVersion>

            <!-- Web App information -->
            <resourceGroup>${RESOURCEGROUP_NAME}</resourceGroup>
            <appName>${WEBAPP_NAME}</appName>
            <region>${REGION}</region>

            <!-- Java Runtime Stack for Web App on Linux-->
            <runtime>
                 <os>linux</os>
                 <javaVersion>jre8</javaVersion>
                 <webContainer>jre8</webContainer>
             </runtime>
             <deployment>
                 <resources>
                 <resource>
                     <directory>${project.basedir}/target</directory>
                     <includes>
                     <include>*.jar</include>
                     </includes>
                 </resource>
                 </resources>
             </deployment>

            <appSettings>
                <property>
                    <name>COSMOSDB_URI</name>
                    <value>${COSMOSDB_URI}</value>
                </property>
                <property>
                    <name>COSMOSDB_KEY</name>
                    <value>${COSMOSDB_KEY}</value>
                </property>
                <property>
                    <name>COSMOSDB_DBNAME</name>
                    <value>${COSMOSDB_DBNAME}</value>
                </property>
                <property>
                    <name>JAVA_OPTS</name>
                    <value>-Dserver.port=80</value>
                </property>
            </appSettings>

        </configuration>
    </plugin>
    ...
</plugins>

部署到 Linux 上的应用服务Deploy to App Service on Linux

使用 azure-webapp:deploy Maven 目标将 TODO 应用部署到 Linux 上的 Azure 应用服务。Use the azure-webapp:deploy Maven goal to deploy the TODO app to Azure App Service on Linux.


# Deploy
bash-3.2$ mvn azure-webapp:deploy
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building spring-todo-app 2.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- azure-webapp-maven-plugin:1.11.0:deploy (default-cli) @ spring-todo-app ---
[INFO] Auth Type : AZURE_CLI, Auth Files : [C:\Users\testuser\.azure\azureProfile.json, C:\Users\testuser\.azure\accessTokens.json]
[INFO] Subscription : xxxxxxxxx
[INFO] Target Web App doesn't exist. Creating a new one...
[INFO] Creating App Service Plan 'ServicePlanb6ba8178-5bbb-49e7'...
[INFO] Successfully created App Service Plan.
[INFO] Successfully created Web App.
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 1 resource to /home/test/e2e-java-experience-in-app-service-linux-part-2/initial/spring-todo-app/target/azure-webapp/spring-todo-app-61bb5207-6fb8-44c4-8230-c1c9e4c099f7
[INFO] Trying to deploy artifact to spring-todo-app...
[INFO] Renaming /home/test/e2e-java-experience-in-app-service-linux-part-2/initial/spring-todo-app/target/azure-webapp/spring-todo-app-61bb5207-6fb8-44c4-8230-c1c9e4c099f7/spring-todo-app-2.0-SNAPSHOT.jar to app.jar
[INFO] Deploying the zip package spring-todo-app-61bb5207-6fb8-44c4-8230-c1c9e4c099f7718326714198381983.zip...
[INFO] Successfully deployed the artifact to https://spring-todo-app.chinacloudsites.cn
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 02:19 min
[INFO] Finished at: 2019-11-06T15:32:03-07:00
[INFO] Final Memory: 50M/574M
[INFO] ------------------------------------------------------------------------

输出包含部署的应用程序的 URL(在本示例中为 https://spring-todo-app.chinacloudsites.cn)。The output contains the URL to your deployed application (in this example, https://spring-todo-app.chinacloudsites.cn ). 可将此 URL 复制到 Web 浏览器,或者在终端窗口中运行以下命令,以加载应用。You can copy this URL into your web browser or run the following command in your Terminal window to load your app.

open https://spring-todo-app.chinacloudsites.cn

在地址栏中,应会看到正在使用远程 URL 运行的应用:You should see the app running with the remote URL in the address bar:

使用远程 URL 运行的 Spring Boot 应用程序

流式传输诊断日志Stream diagnostic logs

若要访问应用服务中的应用程序代码内生成的控制台日志,请在 Azure CLI 中运行以下命令以打开诊断日志记录:To access the console logs generated from inside your application code in App Service, turn on diagnostics logging by running the following command in the Azure CLI:

az webapp log config --resource-group <resource-group-name> --name <app-name> --application-logging true --level Verbose

--level 的可能值为:ErrorWarningInfoVerbosePossible values for --level are: Error, Warning, Info, and Verbose. 每个后续级别包括上一个级别。Each subsequent level includes the previous level. 例如:Error 仅包含错误消息,Verbose 则包含所有消息。For example: Error includes only error messages, and Verbose includes all messages.

启用诊断日志记录功能以后,请运行以下命令来查看日志流:Once diagnostic logging is turned on, run the following command to see the log stream:

az webapp log tail --resource-group <resource-group-name> --name <app-name>

如果没有立即看到控制台日志,请在 30 秒后重新查看。If you don't see console logs immediately, check again in 30 seconds.

备注

也可通过浏览器在 https://<app-name>.scm.chinacloudsites.cn/api/logs/docker 中检查日志文件。You can also inspect the log files from the browser at https://<app-name>.scm.chinacloudsites.cn/api/logs/docker.

若要随时停止日志流式处理,请键入 Ctrl+CTo stop log streaming at any time, type Ctrl+C.

横向扩展 TODO 应用Scale out the TODO App

通过添加另一个辅助角色来横向扩展应用程序:Scale out the application by adding another worker:

az appservice plan update --number-of-workers 2 \
   --name ${WEBAPP_PLAN_NAME} \
   --resource-group <your-azure-group-name>

清理资源Clean up resources

如果不需要将这些资源用于其他教程(请参阅后续步骤),则可通过在 Azure CLI 中运行以下命令将其删除:If you don't need these resources for another tutorial (see Next steps), you can delete them by running the following command in the Azure CLI:    

az group delete --name <your-azure-group-name>

后续步骤Next steps

面向 Java 开发人员的 Azure Spring Boot Spring Data for Cosmos DBAzure Cosmos DBLinux 版应用服务Azure for Java Developers Spring Boot Spring Data for Cosmos DB, Azure Cosmos DB and App Service Linux.

在开发人员指南中详细了解在 Linux 上的应用服务中运行 Java 应用。Learn more about running Java apps on App Service on Linux in the developer guide.