This commit is contained in:
Rade Zheng 2021-04-14 09:33:32 +08:00
Родитель e729f698c2
Коммит f309dcb0dc
31 изменённых файлов: 2206 добавлений и 480 удалений

Просмотреть файл

@ -1,50 +1,53 @@
# 00 - Setup your environment
# 00 - 设置您的环境
__This guide is part of the [Azure Spring Cloud training](../README.md)__
**本教程是[Azure Spring Cloud 培训](../README.md)系列之一**
In this section, we'll set up everything you need to expeditiously complete the training.
在本节中,我们将设置好您快速完成培训所需的一切。
---
## Creating Azure Resources
## 创建Azure资源
To save time, we provide an ARM template for creating all the Azure resources you will need for this lab other than the Azure Spring Cloud instance itself. Use the Deploy to Azure button below.
为了节省时间,我们提供了一个 ARM 模板,用于创建此实验室所需的所有 Azure 资源,而不是 Azure Spring Cloud实例本身。使用下面的"部署到Azure"按钮。
> 💡 Use the following settings for deploying the Azure Template:
> 💡 使用以下设置部署 Azure 模板:
>
> * Create a new resource group.
> * In the location field, select the nearest region from [the list of regions where Azure Spring Cloud is available](https://azure.microsoft.com/global-infrastructure/services/?products=spring-cloud&regions=all).
> * Save the MySQL password you specify in this step. You will need it in section 6. If you don't set one, it will be `super$ecr3t`.
> - 创建新的资源组。
> - 在位置字段中,从[Azure Spring Cloud可用区域列表](https://azure.microsoft.com/global-infrastructure/services/?products=spring-cloud&regions=all)选择,建议选东南亚(SouthEast Asia).
> - 保存您在此步骤中指定的 MySQL 密码。您将需要它在第6节。如果你不设置一个默认是`super$ecr3t`.
[![Deploy to Azure](media/deploybutton.svg)](https://portal.azure.com/#create/Microsoft.Template/uri/https%3A%2F%2Fraw.githubusercontent.com%2Fmicrosoft%2Fazure-spring-cloud-training%2Fmaster%2F00-setup-your-environment%2Fazuredeploy.json?WT.mc_id=azurespringcloud-github-judubois)
[![部署到Azure](media/deploybutton.svg)](https://portal.azure.com/#create/Microsoft.Template/uri/https%3A%2F%2Fraw.githubusercontent.com%2Fmicrosoft%2Fazure-spring-cloud-training%2Fmaster%2F00-setup-your-environment%2Fazuredeploy.json?WT.mc_id=azurespringcloud-github-judubois)
>⏱ The resource provisioning will take some time. __Do not wait!__ Continue with the workshop.
> ⏱资源配置需要一些时间。**不用等待!**继续进行Workshop。
## Prerequisites
## 先决条件
This training lab requires the following to be installed on your machine:
此培训实验要求在您的计算机上安装以下设备:
* [JDK 1.8](https://www.azul.com/downloads/azure-only/zulu/?&version=java-8-lts&architecture=x86-64-bit&package=jdk)
* A text editor or an IDE. If you do not already have an IDE for Java development, we recommend using [Visual Studio Code](https://code.visualstudio.com/?WT.mc_id=azurespringcloud-github-judubois) with the [Java Extension Pack](https://marketplace.visualstudio.com/items?itemName=vscjava.vscode-java-pack&WT.mc_id=azurespringcloud-github-judubois).
- [JDK 1.8](https://www.azul.com/downloads/azure-only/zulu/?&version=java-8-lts&architecture=x86-64-bit&package=jdk)
* The Bash shell. While Azure CLI should behave identically on all environments, shell semantics vary. Therefore, only bash can be used with the commands in this training. To complete this training on Windows, use [Git Bash that accompanies the Windows distribution of Git](https://git-scm.com/download/win). **Use only Git Bash to complete this training on Windows. Do not use WSL, CloudShell, or any other shell.**
- 文本编辑器或IDE。如果您还没有用于Java开发的IDE我们建议使用[Visual Studio Code](https://code.visualstudio.com/?WT.mc_id=azurespringcloud-github-judubois)与[Java Extension Pack](https://marketplace.visualstudio.com/items?itemName=vscjava.vscode-java-pack&WT.mc_id=azurespringcloud-github-judubois).
* [Azure CLI](https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest&WT.mc_id=azurespringcloud-github-judubois) version 2.0.80 or later. You can check the version of your current Azure CLI installation by running:
- Bash Shell. 虽然 Azure CLI 应在所有OS环境中作用相同但 Shell 语法各不相同。因此,只有 bash 才能用于此培训中的命令。要在 Windows 上完成此培训,请使用[Git BashWindows 版本的Git安装包里自带](https://git-scm.com/download/win).**仅使用 Git Bash 在 Windows 上完成此培训。不要使用 WSL、Cloud Shell 或任何其他以外的 Shell 。**
```bash
az --version
```
- [Azure](https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest&WT.mc_id=azurespringcloud-github-judubois)版本2.0.80或更新。您可以通过运行来检查当前 Azure CLI 安装的版本:
> 💡 If you try the command above and you see the error `bash: az: command not found`, run the following command: `alias az='az.cmd'` and try again.
```bash
az --version
#升级到最新版本
az --upgrade --yes
```
* 🚧 The `spring-cloud` extension for Azure CLI. You can install this extension after installing Azure CLI by running `az extension add -n spring-cloud -y`. If the extension is already installed, update it to the latest version by running `az extension update -n spring-cloud`.
> 💡如果你尝试上面的命令,你会看到错误`bash: az: command not found`,运行以下命令:`alias az='az.cmd'`再试一次
> 💡 In sections 9 and 10, you will access the UI of the Microservice applications in a web browser. Use the [new Edge](https://microsoft.com/edge/?WT.mc_id=azurespringcloud-github-judubois), Google Chrome, or Firefox for these sections.
- 🚧`spring-cloud`Azure CLI 的扩展。您可以在安装Azure CLI后通过运行安装此扩展`az extension add -n spring-cloud -y`.如果已安装扩展,请通过运行`az extension update -n spring-cloud` 将其更新到最新版本.
The environment variable `JAVA_HOME` should be set to the path of the JDK installation. The directory specified by this path should have `bin`, `jre`, and `lib` among its subdirectories. Further, ensure your `PATH` variable contains the directory `${JAVA_HOME}/bin`. To test, type `which javac` into bash shell ensure the resulting path points to a file inside `${JAVA_HOME}/bin`.
> 💡 在第 9 节和第 10 节中,您将在 Web 浏览器中访问微服务应用程序的 UI。使用[新Edge](https://microsoft.com/edge/?WT.mc_id=azurespringcloud-github-judubois),谷歌浏览器,或火狐浏览器为这些部分。
You can then use Visual Studio Code or an IDE of your choice.
环境变量`JAVA_HOME`应设置为JDK安装的路径。此路径指定的目录应具有`bin`,`jre`和`lib`在其子目录中。此外,确保您的`PATH`变量包含目录`${JAVA_HOME}/bin`.要测试、键入`which javac`进入bash外 Shell ,确保由此产生的路径指向里面的文件`${JAVA_HOME}/bin`.
然后,您可以使用可视化工作室代码或您选择的 IDE。
---
➡️ Next guide: [01 - Create an Azure Spring Cloud instance](../01-create-an-azure-spring-cloud-instance/README.md)
➡️下一个教程:[01 - 创建Azure Spring Cloud实例](../01-create-an-azure-spring-cloud-instance/README.md)

Просмотреть файл

@ -0,0 +1,50 @@
# 00 - Setup your environment
__This guide is part of the [Azure Spring Cloud training](../README.md)__
In this section, we'll set up everything you need to expeditiously complete the training.
---
## Creating Azure Resources
To save time, we provide an ARM template for creating all the Azure resources you will need for this lab other than the Azure Spring Cloud instance itself. Use the Deploy to Azure button below.
> 💡 Use the following settings for deploying the Azure Template:
>
> * Create a new resource group.
> * In the location field, select the nearest region from [the list of regions where Azure Spring Cloud is available](https://azure.microsoft.com/global-infrastructure/services/?products=spring-cloud&regions=all).
> * Save the MySQL password you specify in this step. You will need it in section 6. If you don't set one, it will be `super$ecr3t`.
[![Deploy to Azure](media/deploybutton.svg)](https://portal.azure.com/#create/Microsoft.Template/uri/https%3A%2F%2Fraw.githubusercontent.com%2Fmicrosoft%2Fazure-spring-cloud-training%2Fmaster%2F00-setup-your-environment%2Fazuredeploy.json?WT.mc_id=azurespringcloud-github-judubois)
>⏱ The resource provisioning will take some time. __Do not wait!__ Continue with the workshop.
## Prerequisites
This training lab requires the following to be installed on your machine:
* [JDK 1.8](https://www.azul.com/downloads/azure-only/zulu/?&version=java-8-lts&architecture=x86-64-bit&package=jdk)
* A text editor or an IDE. If you do not already have an IDE for Java development, we recommend using [Visual Studio Code](https://code.visualstudio.com/?WT.mc_id=azurespringcloud-github-judubois) with the [Java Extension Pack](https://marketplace.visualstudio.com/items?itemName=vscjava.vscode-java-pack&WT.mc_id=azurespringcloud-github-judubois).
* The Bash shell. While Azure CLI should behave identically on all environments, shell semantics vary. Therefore, only bash can be used with the commands in this training. To complete this training on Windows, use [Git Bash that accompanies the Windows distribution of Git](https://git-scm.com/download/win). **Use only Git Bash to complete this training on Windows. Do not use WSL, CloudShell, or any other shell.**
* [Azure CLI](https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest&WT.mc_id=azurespringcloud-github-judubois) version 2.0.80 or later. You can check the version of your current Azure CLI installation by running:
```bash
az --version
```
> 💡 If you try the command above and you see the error `bash: az: command not found`, run the following command: `alias az='az.cmd'` and try again.
* 🚧 The `spring-cloud` extension for Azure CLI. You can install this extension after installing Azure CLI by running `az extension add -n spring-cloud -y`. If the extension is already installed, update it to the latest version by running `az extension update -n spring-cloud`.
> 💡 In sections 9 and 10, you will access the UI of the Microservice applications in a web browser. Use the [new Edge](https://microsoft.com/edge/?WT.mc_id=azurespringcloud-github-judubois), Google Chrome, or Firefox for these sections.
The environment variable `JAVA_HOME` should be set to the path of the JDK installation. The directory specified by this path should have `bin`, `jre`, and `lib` among its subdirectories. Further, ensure your `PATH` variable contains the directory `${JAVA_HOME}/bin`. To test, type `which javac` into bash shell ensure the resulting path points to a file inside `${JAVA_HOME}/bin`.
You can then use Visual Studio Code or an IDE of your choice.
---
➡️ Next guide: [01 - Create an Azure Spring Cloud instance](../01-create-an-azure-spring-cloud-instance/README.md)

Просмотреть файл

@ -1,44 +1,44 @@
# 01 - Create an Azure Spring Cloud instance
# 01 - 创建Azure Spring Cloud实例
__This guide is part of the [Azure Spring Cloud training](../README.md)__
**本教程是[Azure Spring Cloud培训](../README.md)系列之一**
In this section, we'll create an Azure Spring Cloud instance using Azure CLI. While there are other ways of creating Azure resources, Azure CLI is the quickest and simplest method.
在本节中,我们将使用 Azure CLI 创建 Azure Spring Cloud实例。虽然还有其他方法可以创建 Azure 资源,但 Azure CLI 是最快、最简单的方法。
---
## Verify Azure Subscription
## 验证Azure 订阅
Ensure your Azure CLI is logged into your Azure subscription.
确保您在 Azure CLI 中登录到您的 Azure 订阅。
>💡 If using Windows, make sure you enter these commands and all others that follow in Git Bash. **Do not use WSL, CloudShell, or any other shell.**
> 💡如果使用 Windows请确保输入这些命令和 Git Bash 中遵循的所有其他命令。**不要使用 WSL、Cloud Shell或任何其他Shell。**
```bash
az login # Sign into an azure account
az account show # See the currently signed-in account.
```
Ensure your default subscription is the one you intend to use for this lab, and if not - set the subscription via
```az account set --subscription <SUBSCRIPTION_ID>```
确保默认订阅是您打算用于此实验室的订阅,如果不是 - 通过下面命令来指定:
`az account set --subscription <SUBSCRIPTION_ID>`
## Create an Azure Spring Cloud instance
## 创建Azure Spring Cloud实例
In this section, we will create our Azure Spring Cloud instance using Azure CLI.
在本节中,我们将使用 Azure CLI 创建我们的Azure Spring Cloud实例。
First, you will need to come up with a name for your Azure Spring Cloud instance.
首先,您需要为您的 Azure Spring Cloud实例指定一个名称。
- __The name must be unique among all Azure Spring Cloud instances across all of Azure__. Consider using your username as part of the name.
- The name can contain only lowercase letters, numbers and hyphens. The first character must be a letter. The last character must be a letter or number. The value must be between 4 and 32 characters long.
- **这个名字必须在所有Azure的Spring Cloud实例中是独一无二的**.可以考虑使用您的用户名作为名称的一部分。
- 名称只能包含小写字母、数字和连字符。第一个字符必须是字母。最后一个字符必须是字母或数字。长度必须在 4 到 32 个字符之间。
To limit typing, set the variable `AZ_RESOURCE_GROUP` to the name of the resource group created in the previous section. Set the variable `AZ_SPRING_CLOUD_NAME` to the name of the Azure Spring Cloud instance to be created:
为了减少重复输入,设置变量`AZ_RESOURCE_GROUP`到上一节中创建的资源组的名称。设置变量`AZ_SPRING_CLOUD_NAME`要创建的Azure Spring Cloud实例的名称
>🛑 Be sure to substitute your own values for `AZ_RESOURCE_GROUP` and `AZ_SPRING_CLOUD_NAME` as described above. __`AZ_SPRING_CLOUD_NAME` must be globally unique, use lowercase letters and should not have special characters.__
> 🛑如上所述, 一定要用你自己的值来替换`AZ_RESOURCE_GROUP`和`AZ_SPRING_CLOUD_NAME`。**`AZ_SPRING_CLOUD_NAME`必须是全球独一无二的,使用小写字母,不应该有特殊的字符。**
```bash
AZ_RESOURCE_GROUP=spring-cloud-lab
AZ_SPRING_CLOUD_NAME=azure-spring-cloud-lab
```
With these variables set, we can now create the Azure Spring Cloud instance. To enable the Java in-process monitoring agent, we add the `enable-java-agent` flag.
使用这些变量集,我们现在可以创建 Azure Spring Cloud实例。为了启用 Java 进程监控代理,我们添加`enable-java-agent`参数。
```bash
az spring-cloud create \
@ -48,15 +48,17 @@ az spring-cloud create \
--sku standard
```
For the remainder of this workshop, we will be running Azure CLI commands referencing the same resource group and Azure Spring Cloud instance. So let's set them as defaults, so we don't have to specify them again:
在本次Workshop的剩余时间里我们将在Azure CLI里 一直使用同一资源组和 Azure Spring Cloud 实例。因此,我们可以把它们设置为默认值,这样就不必再次指定这些参数:
```bash
az configure --defaults group=$AZ_RESOURCE_GROUP
az configure --defaults spring-cloud=$AZ_SPRING_CLOUD_NAME
```
等Azure Spring Cloud实例创建完可以在Azure Portal里确认并熟悉一下菜单配置。
---
⬅️ Previous guide: [00 - Set Up Your Environment](../00-setup-your-environment/README.md)
⬅️上一个教程:[00 - 设置您的环境](../00-setup-your-environment/README.md)
➡️ Next guide: [02 - Build a simple Spring Boot microservice](../02-build-a-simple-spring-boot-microservice/README.md)
➡️下一个教程:[02 - 构建一个简单的Spring Boot微服务](../02-build-a-simple-spring-boot-microservice/README.md)

Просмотреть файл

@ -0,0 +1,62 @@
# 01 - Create an Azure Spring Cloud instance
__This guide is part of the [Azure Spring Cloud training](../README.md)__
In this section, we'll create an Azure Spring Cloud instance using Azure CLI. While there are other ways of creating Azure resources, Azure CLI is the quickest and simplest method.
---
## Verify Azure Subscription
Ensure your Azure CLI is logged into your Azure subscription.
>💡 If using Windows, make sure you enter these commands and all others that follow in Git Bash. **Do not use WSL, CloudShell, or any other shell.**
```bash
az login # Sign into an azure account
az account show # See the currently signed-in account.
```
Ensure your default subscription is the one you intend to use for this lab, and if not - set the subscription via
```az account set --subscription <SUBSCRIPTION_ID>```
## Create an Azure Spring Cloud instance
In this section, we will create our Azure Spring Cloud instance using Azure CLI.
First, you will need to come up with a name for your Azure Spring Cloud instance.
- __The name must be unique among all Azure Spring Cloud instances across all of Azure__. Consider using your username as part of the name.
- The name can contain only lowercase letters, numbers and hyphens. The first character must be a letter. The last character must be a letter or number. The value must be between 4 and 32 characters long.
To limit typing, set the variable `AZ_RESOURCE_GROUP` to the name of the resource group created in the previous section. Set the variable `AZ_SPRING_CLOUD_NAME` to the name of the Azure Spring Cloud instance to be created:
>🛑 Be sure to substitute your own values for `AZ_RESOURCE_GROUP` and `AZ_SPRING_CLOUD_NAME` as described above. __`AZ_SPRING_CLOUD_NAME` must be globally unique, use lowercase letters and should not have special characters.__
```bash
AZ_RESOURCE_GROUP=spring-cloud-lab
AZ_SPRING_CLOUD_NAME=azure-spring-cloud-lab
```
With these variables set, we can now create the Azure Spring Cloud instance. To enable the Java in-process monitoring agent, we add the `enable-java-agent` flag.
```bash
az spring-cloud create \
-g "$AZ_RESOURCE_GROUP" \
-n "$AZ_SPRING_CLOUD_NAME" \
--enable-java-agent \
--sku standard
```
For the remainder of this workshop, we will be running Azure CLI commands referencing the same resource group and Azure Spring Cloud instance. So let's set them as defaults, so we don't have to specify them again:
```bash
az configure --defaults group=$AZ_RESOURCE_GROUP
az configure --defaults spring-cloud=$AZ_SPRING_CLOUD_NAME
```
---
⬅️ Previous guide: [00 - Set Up Your Environment](../00-setup-your-environment/README.md)
➡️ Next guide: [02 - Build a simple Spring Boot microservice](../02-build-a-simple-spring-boot-microservice/README.md)

Просмотреть файл

@ -1,32 +1,38 @@
# 02 - Build a simple Spring Boot microservice
# 02 - 构建一个简单的Spring Boot微服务
__This guide is part of the [Azure Spring Cloud training](../README.md)__
**本教程是[Azure Spring Cloud 培训](../README.md)系列之一**
In this section, we'll build a simple Spring boot microservice and deploy it to Azure Spring Cloud. This will give us a starting point for adding Spring Cloud technologies in later sections.
在此部分中我们将构建一个简单的Spring Boot微服务并将其部署到 Azure Spring Cloud。这是我们在以后的章节中学习Spring Cloud技术的一个基础前提。
---
## Create a simple Spring Boot microservice
## 创建简单的Spring Boot微服务
The microservice that we create in this guide is [available here](simple-microservice/).
我们在本教程中创建的微服务是[基于这个样例](simple-microservice/), 样例仅供参考,下面我们会一步步把它创建出来.
A typical way to create Spring Boot applications is to use the Spring Initializer at [https://start.spring.io/](https://start.spring.io/). Feel free to explore it outside this training. **For the purposes of this training, we will only invoke the Spring Initializer site via the `curl` command**.
创建Spring Boot应用程序的典型方法是使用Spring Initializer<https://start.spring.io/> . 如果想了解更多,可以看看官方文档或其他教程。**为了这次培训的目的,我们只会使用`curl`命令**.
>💡 __Note:__ All subsequent commands in this workshop should be run from the same directory, except where otherwise indicated via `cd` commands.
> 💡**注意:**本Workshop的所有后续命令应从同一目录运行除非另有指示`cd`命令。
In an __empty__ directory execute the curl command line below:
在一个**空**目录执行下面的 curl 命令行:
```bash
curl https://start.spring.io/starter.tgz -d dependencies=web -d baseDir=simple-microservice -d bootVersion=2.3.8 -d javaVersion=1.8 | tar -xzvf -
```
> We force the Spring Boot version to be 2.3.8.
> 我们强制Spring Boot版本为2.3.8。
## Add a new Spring MVC Controller
## 添加新的Spring MVC Controller
In the `simple-microservice/src/main/java/com/example/demo` directory, create a
new file called `HelloController.java` next to `DemoApplication.java` file with
the following content:
可以在VS Code下操作
```bash
cd simple-microservice
code .
```
在`simple-microservice/src/main/java/com/example/demo`目录,创建一个
新文件`HelloController.java`, 与`DemoApplication.java`文件一起。输入
以下内容:
```java
package com.example.demo;
@ -44,11 +50,11 @@ public class HelloController {
}
```
The final project is available in the ["simple-microservice" folder](simple-microservice/).
最终项目可在["simple-microservice"文件夹](simple-microservice/).
## Test the project locally
## 在本地测试项目
Run the project:
运行项目:
```bash
cd simple-microservice
@ -56,40 +62,40 @@ cd simple-microservice
cd ..
```
Requesting the `/hello` endpoint should return the "Hello from Azure Spring Cloud" message.
请求`/hello` 服务应返回"Hello from Azure Spring Cloud"的消息。
```bash
curl http://127.0.0.1:8080/hello
```
Finally, kill running app:
最后kill运行的应用程序
```bash
kill %1
```
## Create and deploy the application on Azure Spring Cloud
## 在Azure Spring Cloud上创建和部署应用程序
This section shows how to create an app instance and then deploy your code to it.
此部分显示如何创建应用实例,然后将代码部署到其中。
In order to create the app instance graphically, you can use [the Azure portal](https://portal.azure.com/?WT.mc_id=azurespringcloud-github-judubois):
为了以图形方式创建应用实例,您可以使用[Azure Portal](https://portal.azure.com/):
- Look for your Azure Spring Cloud instance in your resource group
- Click on the "Apps" link under "Settings" on the navigation sidebar.
- Click on "Create App" link at the top of the Apps page.
- Create a new application named "simple-microservice"
- 在资源组中查找您的 Azure Spring Cloud实例
- 单击导航侧边栏"设置"下的"应用"链接。
- 单击应用页面顶部的"创建应用"链接。
- 创建名为"simple-microservice"的新应用
![Create application](media/01-create-application.png)
- Click on "Create".
- 单击"创建"。
Alternatively, you can use the command line to create the app instance, which is easier:
或者,您可以使用命令行创建应用实例,这更容易:
```bash
az spring-cloud app create -n simple-microservice
```
You can now build your "simple-microservice" project and deploy it to Azure Spring Cloud:
您现在可以构建您的"simple-microservice"项目,并将其部署到 Azure Spring Cloud
```bash
cd simple-microservice
@ -98,64 +104,62 @@ az spring-cloud app deploy -n simple-microservice --jar-path target/demo-0.0.1-S
cd ..
```
This creates a jar file on your local disk and uploads it to the app instance you created in the preceding step. The `az` command will output a result in JSON. You don't need to pay attention to this output right now, but in the future, you will find it useful for diagnostic and testing purposes.
这将在本地磁盘上创建一个jar文件并将其上传到您在上一步中创建的应用实例。 这`az`命令将在JSON中输出结果。 您现在不需要注意此输出,但将来,您会发现它可用于诊断和测试的。
## Test the project in the cloud
## 在云中测试项目
Go to [the Azure portal](https://portal.azure.com/?WT.mc_id=azurespringcloud-github-judubois):
转到(G)[Azure Portal](https://portal.azure.com/):
- Look for your Azure Spring Cloud instance in your resource group
- Click "Apps" in the "Settings" section of the navigation pane and select "simple-microservice"
- Click on 'See more' to see "Test Endpoint"
![See More](media/02-seemore.png)
- Mouse over the URL labeled as "Test Endpoint" and click the clipboard icon that appears.
This will give you something like:
`https://primary:BBQM6nsYnmmdQREXQINityNx63kWUbjsP7SIvqKhOcWDfP6HJTqg27klMLaSfpTB@rwo1106f.test.azuremicroservices.io/simple-microservice/default/`
>💡 Note the text between `https://` and `@`. These are the basic authentication credentials, without which you will not be authorized to access the service.
- Append `hello/` to the URL. Failure to do this will result in a "404 not found".
- 在资源组中查找您的 Azure Spring Cloud实例
- 单击导航窗格"设置"部分中的"应用",然后选择"simple-microservice"
- 单击"查看更多"以查看"测试终点"
![See More](media/02-seemore.png)
- 网址上的鼠标标记为"测试端点",然后单击显示的剪贴板图标。
这将显示类似的链接:
`https://primary:BBQM6nsYnmmdQREXQINityNx63kWUbjsP7SIvqKhOcWDfP6HJTqg27klMLaSfpTB@rwo1106f.test.azuremicroservices.io/simple-microservice/default/`
> 💡注意之间的文本`https://`和`@`. 这些是基本的身份验证凭据,没有凭据,您将无权访问该服务。
- 点终结点右边的复制,并附加`hello/`到网址末尾。 否则,将导致"找不到404"。
You can now use cURL again to test the `/hello` endpoint, this time served by Azure Spring Cloud. For example.
您现在可以再次使用cURL来测试`/hello`终点这次由Azure Spring Cloud服务。 例如。
```bash
curl https://primary:...simple-microservice/default/hello/
```
If successful, you should see the message: `Hello from Azure Spring Cloud`.
如果成功,您应该看到消息:`Hello from Azure Spring Cloud`.
## Conclusion
## 结论
Congratulations, you have deployed your first Spring Boot microservice to Azure Spring Cloud!
恭喜你你已经部署了你的第一个Spring Boot微服务到Azure Spring Cloud
If you need to check your code, the final project is available in the ["simple-microservice" folder](simple-microservice/).
如果您需要检查您的代码,最终项目可在["simple-microservice"文件夹](simple-microservice/).
Here is the final script to build and deploy everything that was done in this guide:
下面是构建和部署本教程中所做的一切的最终脚本:
```bash
curl https://start.spring.io/starter.tgz -d dependencies=web -d baseDir=simple-microservice -d bootVersion=2.3.8 -d javaVersion=1.8 | tar -xzvf -
cd simple-microservice
cat > HelloController.java << EOF
package com.example.demo;
```
curl https://start.spring.io/starter.tgz -d dependencies=web -d baseDir=simple-microservice -d bootVersion=2.3.8 -d javaVersion=1.8 | tar -xzvf -
cd simple-microservice
cat > HelloController.java << EOF
package com.example.demo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello from Azure Spring Cloud";
@GetMapping("/hello")
public String hello() {
return "Hello from Azure Spring Cloud";
}
}
}
EOF
mv HelloController.java src/main/java/com/example/demo/HelloController.java
az spring-cloud app create -n simple-microservice
./mvnw clean package
az spring-cloud app deploy -n simple-microservice --jar-path target/demo-0.0.1-SNAPSHOT.jar
EOF
mv HelloController.java src/main/java/com/example/demo/HelloController.java
az spring-cloud app create -n simple-microservice
./mvnw clean package
az spring-cloud app deploy -n simple-microservice --jar-path target/demo-0.0.1-SNAPSHOT.jar
```
---
⬅️ Previous guide: [01 - Create an Azure Spring Cloud instance](../01-create-an-azure-spring-cloud-instance/README.md)
⬅️上一个教程:[01 - 创建Azure Spring Cloud实例](../01-create-an-azure-spring-cloud-instance/README.md)
➡️ Next guide: [03 - Configure monitoring](../03-configure-monitoring/README.md)
➡️下一个教程:[03 - 配置监控](../03-configure-monitoring/README.md)

Просмотреть файл

@ -0,0 +1,161 @@
# 02 - Build a simple Spring Boot microservice
__This guide is part of the [Azure Spring Cloud training](../README.md)__
In this section, we'll build a simple Spring boot microservice and deploy it to Azure Spring Cloud. This will give us a starting point for adding Spring Cloud technologies in later sections.
---
## Create a simple Spring Boot microservice
The microservice that we create in this guide is [available here](simple-microservice/).
A typical way to create Spring Boot applications is to use the Spring Initializer at [https://start.spring.io/](https://start.spring.io/). Feel free to explore it outside this training. **For the purposes of this training, we will only invoke the Spring Initializer site via the `curl` command**.
>💡 __Note:__ All subsequent commands in this workshop should be run from the same directory, except where otherwise indicated via `cd` commands.
In an __empty__ directory execute the curl command line below:
```bash
curl https://start.spring.io/starter.tgz -d dependencies=web -d baseDir=simple-microservice -d bootVersion=2.3.8 -d javaVersion=1.8 | tar -xzvf -
```
> We force the Spring Boot version to be 2.3.8.
## Add a new Spring MVC Controller
In the `simple-microservice/src/main/java/com/example/demo` directory, create a
new file called `HelloController.java` next to `DemoApplication.java` file with
the following content:
```java
package com.example.demo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello from Azure Spring Cloud\n";
}
}
```
The final project is available in the ["simple-microservice" folder](simple-microservice/).
## Test the project locally
Run the project:
```bash
cd simple-microservice
./mvnw spring-boot:run &
cd ..
```
Requesting the `/hello` endpoint should return the "Hello from Azure Spring Cloud" message.
```bash
curl http://127.0.0.1:8080/hello
```
Finally, kill running app:
```bash
kill %1
```
## Create and deploy the application on Azure Spring Cloud
This section shows how to create an app instance and then deploy your code to it.
In order to create the app instance graphically, you can use [the Azure portal](https://portal.azure.com/?WT.mc_id=azurespringcloud-github-judubois):
- Look for your Azure Spring Cloud instance in your resource group
- Click on the "Apps" link under "Settings" on the navigation sidebar.
- Click on "Create App" link at the top of the Apps page.
- Create a new application named "simple-microservice"
![Create application](media/01-create-application.png)
- Click on "Create".
Alternatively, you can use the command line to create the app instance, which is easier:
```bash
az spring-cloud app create -n simple-microservice
```
You can now build your "simple-microservice" project and deploy it to Azure Spring Cloud:
```bash
cd simple-microservice
./mvnw clean package
az spring-cloud app deploy -n simple-microservice --jar-path target/demo-0.0.1-SNAPSHOT.jar
cd ..
```
This creates a jar file on your local disk and uploads it to the app instance you created in the preceding step. The `az` command will output a result in JSON. You don't need to pay attention to this output right now, but in the future, you will find it useful for diagnostic and testing purposes.
## Test the project in the cloud
Go to [the Azure portal](https://portal.azure.com/?WT.mc_id=azurespringcloud-github-judubois):
- Look for your Azure Spring Cloud instance in your resource group
- Click "Apps" in the "Settings" section of the navigation pane and select "simple-microservice"
- Click on 'See more' to see "Test Endpoint"
![See More](media/02-seemore.png)
- Mouse over the URL labeled as "Test Endpoint" and click the clipboard icon that appears.
This will give you something like:
`https://primary:BBQM6nsYnmmdQREXQINityNx63kWUbjsP7SIvqKhOcWDfP6HJTqg27klMLaSfpTB@rwo1106f.test.azuremicroservices.io/simple-microservice/default/`
>💡 Note the text between `https://` and `@`. These are the basic authentication credentials, without which you will not be authorized to access the service.
- Append `hello/` to the URL. Failure to do this will result in a "404 not found".
You can now use cURL again to test the `/hello` endpoint, this time served by Azure Spring Cloud. For example.
```bash
curl https://primary:...simple-microservice/default/hello/
```
If successful, you should see the message: `Hello from Azure Spring Cloud`.
## Conclusion
Congratulations, you have deployed your first Spring Boot microservice to Azure Spring Cloud!
If you need to check your code, the final project is available in the ["simple-microservice" folder](simple-microservice/).
Here is the final script to build and deploy everything that was done in this guide:
```
curl https://start.spring.io/starter.tgz -d dependencies=web -d baseDir=simple-microservice -d bootVersion=2.3.8 -d javaVersion=1.8 | tar -xzvf -
cd simple-microservice
cat > HelloController.java << EOF
package com.example.demo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello from Azure Spring Cloud";
}
}
EOF
mv HelloController.java src/main/java/com/example/demo/HelloController.java
az spring-cloud app create -n simple-microservice
./mvnw clean package
az spring-cloud app deploy -n simple-microservice --jar-path target/demo-0.0.1-SNAPSHOT.jar
```
---
⬅️ Previous guide: [01 - Create an Azure Spring Cloud instance](../01-create-an-azure-spring-cloud-instance/README.md)
➡️ Next guide: [03 - Configure monitoring](../03-configure-monitoring/README.md)

Просмотреть файл

@ -1,30 +1,30 @@
# 03 - Configure application logs
# 03 - 配置应用程序日志
__This guide is part of the [Azure Spring Cloud training](../README.md)__
**本教程是[Azure Spring Cloud 培训](../README.md)系列之一**
Now that we have an application deployed, we'll configure Log Analytics, so that we can quickly search the application's logs if something goes wrong. We'll see how to take advantage of Log Analytics in a later section, but because it takes time for log entries to start coming in, we'll do the configuration steps here before moving on with the training.
现在,我们部署了一个应用程序,我们将配置日志分析,以便如果出了问题,我们可以快速搜索应用程序的日志。我们将在稍后部分查看如何使用日志分析(Log Analytics),但由于日志条目的收集会有些延后,我们将先配置收集日志,再继续后面的培训。
---
## Configure log aggregation
## 配置日志聚合
There are actually three ways to access your application's logs: [Azure Storage](https://docs.microsoft.com/en-us/azure/storage/common/storage-introduction/?WT.mc_id=azurespringcloud-github-judubois), [Azure Events Hub](https://docs.microsoft.com/en-us/azure/event-hubs/?WT.mc_id=azurespringcloud-github-judubois), and [Log Analytics](https://docs.microsoft.com/en-us/azure/azure-monitor/log-query/get-started-portal/?WT.mc_id=azurespringcloud-github-judubois). We will focus here on Log Analytics as it's the most common one, and as it's integrated into Azure Spring Cloud.
实际上,有三种方法可以访问您的应用程序的日志:[Azure存储](https://docs.microsoft.com/en-us/azure/storage/common/storage-introduction/?WT.mc_id=azurespringcloud-github-judubois),[Azure活动中心](https://docs.microsoft.com/en-us/azure/event-hubs/?WT.mc_id=azurespringcloud-github-judubois)和[日志分析](https://docs.microsoft.com/en-us/azure/azure-monitor/log-query/get-started-portal/?WT.mc_id=azurespringcloud-github-judubois).我们将专注于日志分析因为它是最常见的并且已集成到Azure Spring Cloud中。
[Log Analytics](https://docs.microsoft.com/en-us/azure/azure-monitor/log-query/get-started-portal/?WT.mc_id=azurespringcloud-github-judubois) is part of [Azure Monitor](https://azure.microsoft.com/en-us/services/monitor/?WT.mc_id=azurespringcloud-github-judubois), which is well-integrated into Azure Spring Cloud and which we will also use for metrics monitoring.
[日志分析](https://docs.microsoft.com/en-us/azure/azure-monitor/log-query/get-started-portal/?WT.mc_id=azurespringcloud-github-judubois)是[Azure Monitor](https://azure.microsoft.com/en-us/services/monitor/?WT.mc_id=azurespringcloud-github-judubois)中的一部分也已经很好地集成到Azure Spring Cloud我们也将用来做指标监测。
Having completed the setup in [Section 00](../00-setup-your-environment/README.md), you should have a Log Analytics workspace named `sclab-la-<unique string>` in your resource group for this workshop. We must now configure our Azure Spring Cloud instance to send its data to this workspace.
完成[第 00 节](../00-setup-your-environment/README.md)的设置后,您应该有一个日志分析工作区命名`sclab-la-<unique string>`在您的资源组。我们现在必须配置 Azure Spring Cloud实例将其数据发送到此工作区。
- Navigate to the Azure Spring Cloud instance in Azure Portal and select "Diagnostic settings" in the "Monitoring" section of the navigation pane:
- 导航到 Azure 门户中的 Azure Spring Cloud实例并在导航窗格的"监控"部分选择"诊断设置"
[![Diagnostic Settings](media/01-diagnostic-settings.png)]
\[![Diagnostic Settings](media/01-diagnostic-settings.png)]
- Click on "Add diagnostic setting" and configure your instance to send all its logs to the Log analytics workspace that we just created.
- Fill in the values as shown here and click "Save".
- 单击"添加诊断设置"并配置您的实例,将其**所有**日志发送到我们刚刚创建的日志分析工作区。
- 填写此处显示的值并单击"保存"。
![Send logs to the log analytics workspace](media/02-send-logs-to-log-analytics-workspace.png)
---
⬅️ Previous guide: [02 - Build a simple Spring Boot microservice](../02-build-a-simple-spring-boot-microservice/README.md)
⬅️上一个教程:[02 - 构建一个简单的Spring Boot微服务](../02-build-a-simple-spring-boot-microservice/README.md)
➡️ Next guide: [04 - Configure a Spring Cloud Config server](../04-configure-a-spring-cloud-config-server/README.md)
➡️下一个教程:[04 - 配置Spring Cloud Config Server](../04-configure-a-spring-cloud-config-server/README.md)

Просмотреть файл

@ -0,0 +1,30 @@
# 03 - Configure application logs
__This guide is part of the [Azure Spring Cloud training](../README.md)__
Now that we have an application deployed, we'll configure Log Analytics, so that we can quickly search the application's logs if something goes wrong. We'll see how to take advantage of Log Analytics in a later section, but because it takes time for log entries to start coming in, we'll do the configuration steps here before moving on with the training.
---
## Configure log aggregation
There are actually three ways to access your application's logs: [Azure Storage](https://docs.microsoft.com/en-us/azure/storage/common/storage-introduction/?WT.mc_id=azurespringcloud-github-judubois), [Azure Events Hub](https://docs.microsoft.com/en-us/azure/event-hubs/?WT.mc_id=azurespringcloud-github-judubois), and [Log Analytics](https://docs.microsoft.com/en-us/azure/azure-monitor/log-query/get-started-portal/?WT.mc_id=azurespringcloud-github-judubois). We will focus here on Log Analytics as it's the most common one, and as it's integrated into Azure Spring Cloud.
[Log Analytics](https://docs.microsoft.com/en-us/azure/azure-monitor/log-query/get-started-portal/?WT.mc_id=azurespringcloud-github-judubois) is part of [Azure Monitor](https://azure.microsoft.com/en-us/services/monitor/?WT.mc_id=azurespringcloud-github-judubois), which is well-integrated into Azure Spring Cloud and which we will also use for metrics monitoring.
Having completed the setup in [Section 00](../00-setup-your-environment/README.md), you should have a Log Analytics workspace named `sclab-la-<unique string>` in your resource group for this workshop. We must now configure our Azure Spring Cloud instance to send its data to this workspace.
- Navigate to the Azure Spring Cloud instance in Azure Portal and select "Diagnostic settings" in the "Monitoring" section of the navigation pane:
[![Diagnostic Settings](media/01-diagnostic-settings.png)]
- Click on "Add diagnostic setting" and configure your instance to send all its logs to the Log analytics workspace that we just created.
- Fill in the values as shown here and click "Save".
![Send logs to the log analytics workspace](media/02-send-logs-to-log-analytics-workspace.png)
---
⬅️ Previous guide: [02 - Build a simple Spring Boot microservice](../02-build-a-simple-spring-boot-microservice/README.md)
➡️ Next guide: [04 - Configure a Spring Cloud Config server](../04-configure-a-spring-cloud-config-server/README.md)

Просмотреть файл

@ -1,77 +1,81 @@
# 04 - Configure a Spring Cloud Config server
# 04 - 配置Spring Cloud Config Server
__This guide is part of the [Azure Spring Cloud training](../README.md)__
**本教程是[Azure Spring Cloud 培训](../README.md)系列之一**
A key feature of cloud-native applications is *externalized configuration* - the ability to store, manage, and version configuration separately from the application code. In this section, we'll configure a [Spring Cloud Config Server](https://cloud.spring.io/spring-cloud-config) to enable this functionality. In the next section, you'll see how Spring Cloud Config can inject configuration from a Git repository into your application.
云原生应用程序的一个关键功能是*外部化配置*-能够将配置与应用程序代码分开,进行独立的存储、管理和版本化。在此部分中,我们将配置[Spring Cloud Config Server](https://cloud.spring.io/spring-cloud-config)启用此功能。在下一节中您将看到Spring Cloud Config 如何从 Git 存储库向您的应用程序注入配置。
---
> 💡 If your organization uses Azure Repos as your source code repository, see [Using Azure Repos for Azure Spring Cloud configuration](AzureReposForConfig.md)
> 💡 如果您的组织使用 Azure 存储库(Repos)作为源代码存储库,请参阅[使用Azure Repos进行Azure Spring Cloud配置](AzureReposForConfig.md)
> ⏱ If you want to skip the step of creating a private repository, you can use this public repository instead: [https://github.com/Azure-Samples/spring-cloud-sample-public-config.git](https://github.com/Azure-Samples/spring-cloud-sample-public-config.git). __Storing configuration in a public repository is not recommended in real-world deployments.__ We offer this public repository only as a shortcut for this workshop, for example if you don't have a GitHub account.
> ⏱如果您想跳过创建私有存储库的步骤,您可以改用此公共存储库:<https://github.com/Azure-Samples/spring-cloud-sample-public-config.git>.**在真实世界部署中不建议将配置存储在公共存储库中。**我们仅提供此公共存储库作为本次Workshop的实验便利例如如果您没有 GitHub 帐户。
>
> To use this shortcut:
> - Go to [the Azure portal](https://portal.azure.com/?WT.mc_id=azurespringcloud-github-judubois).
> - Go to the overview page of your Azure Spring Cloud server and select "Config server" in the menu
> - Set the repository URL: `https://github.com/Azure-Samples/spring-cloud-sample-public-config.git`
> - Click on "Validate" and wait for the operation to succeed
> - Click on "Apply" and wait for the operation to succeed
>
> We have enabled Azure Spring Cloud to create a configuration server with the configuration files from this repository. You can now proceed to the next guide:
> ➡ [05 - Build a Spring Boot microservice using Spring Cloud features](../05-build-a-spring-boot-microservice-using-spring-cloud-features/README.md)
> 要使用此快捷方式:
>
> - 转到(G)[Azure门户网站](https://portal.azure.com/).
> - 转到 Azure Spring Cloud服务器的概述页面并在菜单中选择" Config Server"
> - 设置存储库网址:`https://github.com/Azure-Samples/spring-cloud-sample-public-config.git`
> - 单击"验证"并等待操作成功
> - 单击"应用"并等待操作成功
>
> 我们已启用 Azure Spring Cloud创建 Config Server其中包含来自此存储库的配置文件。现在您可以继续阅读下一个教程
> ➡[05 - 使用Spring Cloud功能构建Spring Boot微服务](../05-build-a-spring-boot-microservice-using-spring-cloud-features/README.md)
## Create a Git repository for storing the application configuration
## 创建用于存储应用程序配置的 Git 存储库
On your [GitHub account](https://github.com), create a new **private** repository where the Spring Boot configurations will be stored.
在你的[Github帐户](https://github.com),创建一个新的**私人**存储库用来作为Spring Boot配置的存储库。
In the new private GitHub repository, add a new `application.yml` file which will store configuration data for all our microservices.
在新的私人 GitHub 存储库中,添加新的`application.yml`文件将存储配置数据为我们所有的微服务。
Typically, each Spring Boot application includes such a file within the application binaries to contain application settings. A Spring Cloud Configuration Server allow such settings to be stored at a single location and served from a single source.
通常每个Spring Boot应用程序在打包文件中都包含有类似文件用来作为应用程序配置。Spring Cloud Config Server允许将此类设置集中存储在单个位置来实现配置集中化管理。
For the moment, our `application.yml` will just store a message to check if the configuration is successful:
现在,我们的`application.yml`将只存储一条消息,以检查配置是否成功:
```yaml
application:
message: Configured by Azure Spring Cloud
```
Commit and push the new file.
commit并push修改的文件。
## Create a GitHub personal token
## 创建 GitHub 私有 Token
Azure Spring Cloud can access Git repositories that are public, secured by SSH, or secured using HTTP basic authentication. We will use that last option, as it is easier to create and manage with GitHub.
Azure Spring Cloud可以访问公共、由 SSH 保护或使用 HTTP 基本身份验证进行保护的 Git 存储库。我们将使用最后一个选项因为这样在Github上更容易创建和管理GitHub。
Follow the [GitHub guide to create a personal token](https://help.github.com/en/articles/creating-a-personal-access-token-for-the-command-line) and save your token. When asked to select scopes, check off the entire "repo" section (as shown below) and nothing else.
参考[GitHub 教程以创建私有访问token](https://help.github.com/en/articles/creating-a-personal-access-token-for-the-command-line),并保存您的令牌。当被要求选择范围(Scope)时,请选择整个"Repo(库)"部分(如下所示),这样就完成了。
![GitHub personal access token](media/01-github-personal-access-token.png)
Once the token is generated, leave that tab open until the end of this section.
生成令牌后,将该选项卡保持打开状态,直到本节结束。
## Configure Azure Spring Cloud to access the Git repository
## 配置 Azure Spring Cloud以访问 Git 存储库
- Go to [the Azure portal](https://portal.azure.com/?WT.mc_id=azurespringcloud-github-judubois).
- Go to the overview page of your Azure Spring Cloud server and select "Config server" in the menu
- Configure the repository we previously created:
- Add the repository URL, for example `https://github.com/Azure-Samples/spring-cloud-sample-public-config.git`
- 转到(G)[Azure门户网站](https://portal.azure.com/?WT.mc_id=azurespringcloud-github-judubois).
- 转到 Azure Spring Cloud服务器的概述页面并在菜单中选择" Config Server"
- 配置我们以前创建的存储库:
>💡 Make sure you include the `.git` ending in the URL.
- 例如,添加存储库 URL`https://github.com/Azure-Samples/spring-cloud-sample-public-config.git`
- Click on `Authentication` and select `HTTP Basic`
- The __username__ is your GitHub login name
- The __password__ is the personal token we created in the previous section
- Click on "Validate" and wait for the operation to succeed
- Click on "Apply" and wait for the operation to succeed
> 💡确保您包括`.git`以网址结尾。
- 单击`Authentication`并选择`HTTP Basic`
- 这**用户名**是您的GitHub登录名
- 这**密码**是我们在前一节创建的个人令牌
- 单击"验证"并等待操作成功
- 单击"应用"并等待操作成功
![Spring Cloud config server](media/02-config-server.png)
## Review
## 回顾
We have now created a private configuration repository. We have enabled Azure Spring Cloud to create a configuration server with the configuration files from this repository.
我们现在创建了一个私人配置存储库。我们已启用 Azure Spring Cloud创建 Config Server其中包含来自此存储库的配置文件。
In the next section, we will create an application that consumes this configuration, specifically the custom message we defined in `application.yml`.
在下一节中,我们将创建一个应用程序来使用此配置,特别是我们在定义的自定义消息`application.yml`.
---
⬅️ Previous guide: [03 - Configure application logs](../03-configure-monitoring/README.md)
⬅️上一个教程:[03 - 配置应用程序日志](../03-configure-monitoring/README.md)
➡️ Next guide: [05 - Build a Spring Boot microservice using Spring Cloud features](../05-build-a-spring-boot-microservice-using-spring-cloud-features/README.md)
➡️下一个教程:[05 - 使用Spring Cloud功能构建Spring Boot微服务](../05-build-a-spring-boot-microservice-using-spring-cloud-features/README.md)

Просмотреть файл

@ -0,0 +1,77 @@
# 04 - Configure a Spring Cloud Config server
__This guide is part of the [Azure Spring Cloud training](../README.md)__
A key feature of cloud-native applications is *externalized configuration* - the ability to store, manage, and version configuration separately from the application code. In this section, we'll configure a [Spring Cloud Config Server](https://cloud.spring.io/spring-cloud-config) to enable this functionality. In the next section, you'll see how Spring Cloud Config can inject configuration from a Git repository into your application.
---
> 💡 If your organization uses Azure Repos as your source code repository, see [Using Azure Repos for Azure Spring Cloud configuration](AzureReposForConfig.md)
> ⏱ If you want to skip the step of creating a private repository, you can use this public repository instead: [https://github.com/Azure-Samples/spring-cloud-sample-public-config.git](https://github.com/Azure-Samples/spring-cloud-sample-public-config.git). __Storing configuration in a public repository is not recommended in real-world deployments.__ We offer this public repository only as a shortcut for this workshop, for example if you don't have a GitHub account.
>
> To use this shortcut:
> - Go to [the Azure portal](https://portal.azure.com/?WT.mc_id=azurespringcloud-github-judubois).
> - Go to the overview page of your Azure Spring Cloud server and select "Config server" in the menu
> - Set the repository URL: `https://github.com/Azure-Samples/spring-cloud-sample-public-config.git`
> - Click on "Validate" and wait for the operation to succeed
> - Click on "Apply" and wait for the operation to succeed
>
> We have enabled Azure Spring Cloud to create a configuration server with the configuration files from this repository. You can now proceed to the next guide:
> ➡ [05 - Build a Spring Boot microservice using Spring Cloud features](../05-build-a-spring-boot-microservice-using-spring-cloud-features/README.md)
## Create a Git repository for storing the application configuration
On your [GitHub account](https://github.com), create a new **private** repository where the Spring Boot configurations will be stored.
In the new private GitHub repository, add a new `application.yml` file which will store configuration data for all our microservices.
Typically, each Spring Boot application includes such a file within the application binaries to contain application settings. A Spring Cloud Configuration Server allow such settings to be stored at a single location and served from a single source.
For the moment, our `application.yml` will just store a message to check if the configuration is successful:
```yaml
application:
message: Configured by Azure Spring Cloud
```
Commit and push the new file.
## Create a GitHub personal token
Azure Spring Cloud can access Git repositories that are public, secured by SSH, or secured using HTTP basic authentication. We will use that last option, as it is easier to create and manage with GitHub.
Follow the [GitHub guide to create a personal token](https://help.github.com/en/articles/creating-a-personal-access-token-for-the-command-line) and save your token. When asked to select scopes, check off the entire "repo" section (as shown below) and nothing else.
![GitHub personal access token](media/01-github-personal-access-token.png)
Once the token is generated, leave that tab open until the end of this section.
## Configure Azure Spring Cloud to access the Git repository
- Go to [the Azure portal](https://portal.azure.com/?WT.mc_id=azurespringcloud-github-judubois).
- Go to the overview page of your Azure Spring Cloud server and select "Config server" in the menu
- Configure the repository we previously created:
- Add the repository URL, for example `https://github.com/Azure-Samples/spring-cloud-sample-public-config.git`
>💡 Make sure you include the `.git` ending in the URL.
- Click on `Authentication` and select `HTTP Basic`
- The __username__ is your GitHub login name
- The __password__ is the personal token we created in the previous section
- Click on "Validate" and wait for the operation to succeed
- Click on "Apply" and wait for the operation to succeed
![Spring Cloud config server](media/02-config-server.png)
## Review
We have now created a private configuration repository. We have enabled Azure Spring Cloud to create a configuration server with the configuration files from this repository.
In the next section, we will create an application that consumes this configuration, specifically the custom message we defined in `application.yml`.
---
⬅️ Previous guide: [03 - Configure application logs](../03-configure-monitoring/README.md)
➡️ Next guide: [05 - Build a Spring Boot microservice using Spring Cloud features](../05-build-a-spring-boot-microservice-using-spring-cloud-features/README.md)

Просмотреть файл

@ -1,36 +1,36 @@
# 05 - Build a Spring Boot microservice using Spring Cloud features
# 05 - 使用Spring Cloud功能构建Spring Boot微服务
__This guide is part of the [Azure Spring Cloud training](../README.md)__
**本教程是[Azure Spring Cloud 培训](../README.md)系列之一**
In this section, we'll build a similar service to the one from section 2, but with the addition of two important Spring Cloud features. First, we'll add this service to Spring Cloud registry for discovery by other services. Second, we'll use Spring Cloud Config to inject a setting from a Git repository into the application and display it on the screen.
在此部分中,我们将构建与第 2 节中的类似服务但增加了两个重要的Spring Cloud功能。首先我们将此服务添加到Spring Cloud注册表供其他服务发现。其次我们将使用Spring Cloud Config将 Git 存储库中的设置注入应用程序,并将其显示在屏幕上。
---
## What we are going to build
## 我们要建立什么
This guide builds upon the previous guides: we are going to build again a simple Spring Boot microservice like in [02 - Build a simple Spring Boot microservice](../02-build-a-simple-spring-boot-microservice/README.md), but this time it will use two major Spring Cloud features:
本教程建立在以前的教程我们将再次建立一个简单的Sping Boot微服务如在[02 - 构建一个简单的Spring Boot微服务](../02-build-a-simple-spring-boot-microservice/README.md)但这次它将使用两个主要的Spring Cloud功能
- It will be connected to a Spring Cloud Service Registry so it can discover other microservices, as well as being discovered itself!
- 它将连接到一个Sping Cloud Service Registry以便它可以发现其他微服务以及本身被发现
- It will get its configuration from the Spring Cloud Config server that we configured in the previous guide, [04 - Configure a Spring Cloud Config server](../04-configure-a-spring-cloud-config-server/README.md)
- 它将从我们在上一个教程中配置的Sping Cloud Config Server获得配置[04 - 配置Sping Cloud Config服务器](../04-configure-a-spring-cloud-config-server/README.md)
For both features, it will just be a matter of adding an official Spring Boot starter, and Azure Spring Cloud will take care of everything else.
对于这两个功能其实就是添加官方Spring Boot starter就能实现的简单问题Azure Spring Cloud会负责解决一切其他相关的底层功能。
## Create a simple Spring Cloud microservice
## 创建简单的Spring Cloud微服务
The microservice that we create in this guide is [available here](spring-cloud-microservice/).
我们在本教程中创建的微服务[在这里](spring-cloud-microservice/).
To create our microservice, we will invoke the Spring Initalizer service from the command line:
为了创建我们的微服务我们将从命令行调用Sping Initalizer服务
```bash
curl https://start.spring.io/starter.tgz -d dependencies=web,cloud-eureka,cloud-config-client -d baseDir=spring-cloud-microservice -d bootVersion=2.3.8 -d javaVersion=1.8 | tar -xzvf -
```
> This time, we add the `Eureka Discovery Client` and the `Config Client` Spring Boot starters, which will respectively automatically trigger the use of Spring Cloud Service Registry and the Spring Cloud Config Server.
> 这一次,我们添加`Eureka Discovery Client`和`Config Client`Spring Boot starters将分别自动使用自带的Spring Cloud服务注册表和Spring Cloud配置服务器。
## Add a new Spring MVC Controller
## 添加新的Sping MVC 控制器
Next to the DemoApplication class, create a new class called `HelloController` with the following content:
可以使用VS Code打开在DemoApplication类同一目录下创建一个新类名为`HelloController`内容如下:
```java
package com.example.demo;
@ -52,15 +52,15 @@ public class HelloController {
}
```
## Test the project locally
## 在本地测试项目
Before deploying the microservice to Azure Spring Cloud, let's run it locally.
在将微服务部署到 Azure Spring Cloud之前我们先在本地运行一下。
>💡 Do not be alarmed when you see exception stack traces:
> 💡当您看到异常堆栈(Exception)日志时,不要惊慌:
> ![Exception stack trace](media/01-exception-stack-trace.png)
>Spring Cloud is attempting to contact a local configuration server, which we have not provided. The application will still start using any available local settings and defaults.
> 那是因为Spring Cloud正在尝试连接我们尚未提供的本地配置服务器。该应用程序仍可使用本地设置和默认值正常运行。
To run `simple-cloud-microservice` locally:
运行`simple-cloud-microservice`本地:
```bash
cd spring-cloud-microservice
@ -68,27 +68,27 @@ cd spring-cloud-microservice
cd ..
```
Requesting the `/hello` endpoint should return the "Not configured by a Spring Cloud Server" message.
请求`/hello` Endpoint 应返回"Not configured by a Spring Cloud Server"消息。
```bash
curl http://127.0.0.1:8080/hello
```
Kill the locally running microservice:
kill本地运行的微服务
```bash
kill %1
```
## Create and deploy the application on Azure Spring Cloud
## 在Azure Spring Cloud上创建和部署应用程序
As in [02 - Build a simple Spring Boot microservice](../02-build-a-simple-spring-boot-microservice/README.md), create a specific `spring-cloud-microservice` application in your Azure Spring Cloud instance:
如在[02 - 构建一个简单的Spring Boot微服务](../02-build-a-simple-spring-boot-microservice/README.md),创建一个特定的`spring-cloud-microservice`应用在您的Azure Spring Cloud实例中
```bash
az spring-cloud app create -n spring-cloud-microservice
```
You can now build your "spring-cloud-microservice" project and send it to Azure Spring Cloud:
现在,您可以构建您的"Spring Cloud微服务"项目,并将其部署到 Azure Spring Cloud
```bash
cd spring-cloud-microservice
@ -97,53 +97,53 @@ az spring-cloud app deploy -n spring-cloud-microservice --jar-path target/demo-0
cd ..
```
## Test the project in the cloud
## 在云中测试项目
Go to [the Azure portal](https://portal.azure.com/?WT.mc_id=azurespringcloud-github-judubois):
转到(G)[Azure Portal](https://portal.azure.com/):
- Look for your Azure Spring Cloud instance in your resource group
- Go to "Apps"
- Verify that `spring-cloud-microservice` has a `Registration status` of `1/1`. This shows that it is correctly registered in Spring Cloud Service Registry.
- Select `spring-cloud-microservice` to have more information on the microservice.
- Copy/paste the "Test Endpoint" that is provided.
- 在资源组中查找您的 Azure Spring Cloud实例
- 转到"应用"
- 验证`spring-cloud-microservice`有一个`Registration status`之`1/1`.这表明它在Spring Cloud Service Registry注册成功。
- 选择`spring-cloud-microservice`了解有关微服务的更多信息。
- 复制/粘贴提供的"测试终点"。
You can now use cURL again to test the `/hello` endpoint, this time it is served by Azure Spring Cloud and configured using the Spring Config Server from [04 - Configure a Spring Cloud Config server](../04-configure-a-spring-cloud-config-server/README.md).
您现在可以再次使用cURL来测试`/hello`端点这一次它是由Azure Spring Cloud服务并配置使用Sping 配置服务器从[04 - 配置Sping Cloud Config服务器](../04-configure-a-spring-cloud-config-server/README.md).
As a result, requesting the `/hello` endpoint should return the message that we configured in the `application.yml` file, coming from the Spring Cloud Config Server:
因此,请求`/hello`端点应返回我们在`application.yml`文件来自Sping Cloud Config服务器
```bash
Configured by Azure Spring Cloud
```
## Stream application logs
## 流式传输应用程序日志
When you run an application on your machine, you can see its output in the console. When you run a microservice on Azure Spring Cloud, you can also see its console output through Azure CLI:
当您在计算机上运行应用程序时,您可以在主机上看到它的输出。当您在 Azure Spring Cloud上运行微服务时您还可以通过 Azure CLI 查看其控制台输出:
```bash
az spring-cloud app logs --name spring-cloud-microservice -f
```
_Please be aware it might take a couple of minutes for the logs to show up._
_请注意,日志可能需要几分钟才能显示出来。_
You should see the console output of `spring-cloud-microservice` scroll by on your terminal:
您应该看到控制台输出`spring-cloud-microservice`在终端上滚动:
![Console output](media/02-console-output.png)
Press CTRL+C to stop following the output and return to the shell.
按 CTRL+C 停止跟随输出并返回Shell。
## Query application logs
## 查询应用程序日志
Streaming the console output as we just did may be helpful in understanding the immediate state of a microservice. However, sometimes it's necessary to look further into the past or to look for something specific. This is easily done with Log Analytics. In section 3, we enabled log aggregation in Azure Log Analytics. Such settings changes can take 1-2 minutes to apply, so by now, you should be able to query Azure Log Analytics.
像我们刚才所做的那样流式处理控制台输出可能有助于了解微服务的即时状态。然而,有时有必要进一步回顾过去或寻找一些具体的东西。这很容易通过日志分析来完成。在第 3 节中,我们启用了 Azure 日志分析中的日志聚合。此类设置更改可能需要 1-2 分钟才能应用,因此,到现在,您应该能够查询 Azure 日志分析。
[Open Azure Portal](https://portal.azure.com/?WT.mc_id=azurespringcloud-github-judubois) and navigate to your Azure Spring Cloud instance. Click on "Logs". This is a shortcut to the Log Analytics workspace that was created earlier. If a tutorial appears, feel free to skip it for now.
[打开Azure Portal](https://portal.azure.com/)并导航到您的Azure Spring Cloud实例。单击"日志"。这是之前创建的日志分析工作区的快捷方式。如果出现教程,可以随时跳过它。
This workspace allows you to run queries on the aggregated logs. The most common query is to get the latest log from a specific application:
此工作区允许您在聚合日志上运行查询。最常见的查询是从特定应用程序获取最新日志:
__Important:__ Spring Boot applications logs have a dedicated `AppPlatformLogsforSpring` type.
**重要:**Spring Boot应用程序日志具有专用`AppPlatformLogsforSpring`类型。
Here is how to get its 50 most recent logs of the `AppPlatformLogsforSpring` type for the microservice we just deployed:
下面是如何获得其50最新的日志`AppPlatformLogsforSpring`我们刚刚部署的微服务类型:
Insert this text in the text area that states "Type your queries here or click on of the example queries to start". Click the text of the query, then click "Run".
将此文本插入文本区域,其中指出"在此处键入您的查询或单击要开始的示例查询"。 单击查询的文本,然后单击"运行"。
```sql
AppPlatformLogsforSpring
@ -155,16 +155,16 @@ AppPlatformLogsforSpring
![Query logs](media/03-logs-query.png)
>💡 It can also take 1-2 minutes for the console output of an Azure Spring Cloud microservice to be read into Log Analytics.
> 💡 Azure Spring Cloud微服务的控制台输出也可能需要 1-2 分钟才能读入日志分析。
## Conclusion
## 结论
Congratulations, you have deployed a complete Spring Cloud microservice, using Spring Cloud Service Registry and Spring Cloud Config Server!
恭喜您您已经部署了完整的Spring Cloud微服务使用Spring Cloud服务注册表和Spring Cloud配置服务器
If you need to check your code, the final project is available in the ["spring-cloud-microservice" folder](spring-cloud-microservice/).
如果您需要检查您的代码,最终项目可在["Spring Cloud Microservice"文件夹](spring-cloud-microservice/).
---
⬅️ Previous guide: [04 - Configure a Spring Cloud Config server](../04-configure-a-spring-cloud-config-server/README.md)
⬅️上一个教程:[04 - 配置Sping Cloud Config服务器](../04-configure-a-spring-cloud-config-server/README.md)
➡️ Next guide: [06 - Build a reactive Spring Boot microservice using Cosmos DB](../06-build-a-reactive-spring-boot-microservice-using-cosmosdb/README.md)
➡️下一个教程:[06 - 使用Cosmos DB 构建 Reactive Spring Boot微服务](../06-build-a-reactive-spring-boot-microservice-using-cosmosdb/README.md)

Просмотреть файл

@ -0,0 +1,170 @@
# 05 - Build a Spring Boot microservice using Spring Cloud features
__This guide is part of the [Azure Spring Cloud training](../README.md)__
In this section, we'll build a similar service to the one from section 2, but with the addition of two important Spring Cloud features. First, we'll add this service to Spring Cloud registry for discovery by other services. Second, we'll use Spring Cloud Config to inject a setting from a Git repository into the application and display it on the screen.
---
## What we are going to build
This guide builds upon the previous guides: we are going to build again a simple Spring Boot microservice like in [02 - Build a simple Spring Boot microservice](../02-build-a-simple-spring-boot-microservice/README.md), but this time it will use two major Spring Cloud features:
- It will be connected to a Spring Cloud Service Registry so it can discover other microservices, as well as being discovered itself!
- It will get its configuration from the Spring Cloud Config server that we configured in the previous guide, [04 - Configure a Spring Cloud Config server](../04-configure-a-spring-cloud-config-server/README.md)
For both features, it will just be a matter of adding an official Spring Boot starter, and Azure Spring Cloud will take care of everything else.
## Create a simple Spring Cloud microservice
The microservice that we create in this guide is [available here](spring-cloud-microservice/).
To create our microservice, we will invoke the Spring Initalizer service from the command line:
```bash
curl https://start.spring.io/starter.tgz -d dependencies=web,cloud-eureka,cloud-config-client -d baseDir=spring-cloud-microservice -d bootVersion=2.3.8 -d javaVersion=1.8 | tar -xzvf -
```
> This time, we add the `Eureka Discovery Client` and the `Config Client` Spring Boot starters, which will respectively automatically trigger the use of Spring Cloud Service Registry and the Spring Cloud Config Server.
## Add a new Spring MVC Controller
Next to the DemoApplication class, create a new class called `HelloController` with the following content:
```java
package com.example.demo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@Value("${application.message:Not configured by a Spring Cloud Server}")
private String message;
@GetMapping("/hello")
public String hello() {
return message + '\n';
}
}
```
## Test the project locally
Before deploying the microservice to Azure Spring Cloud, let's run it locally.
>💡 Do not be alarmed when you see exception stack traces:
> ![Exception stack trace](media/01-exception-stack-trace.png)
>Spring Cloud is attempting to contact a local configuration server, which we have not provided. The application will still start using any available local settings and defaults.
To run `simple-cloud-microservice` locally:
```bash
cd spring-cloud-microservice
./mvnw spring-boot:run &
cd ..
```
Requesting the `/hello` endpoint should return the "Not configured by a Spring Cloud Server" message.
```bash
curl http://127.0.0.1:8080/hello
```
Kill the locally running microservice:
```bash
kill %1
```
## Create and deploy the application on Azure Spring Cloud
As in [02 - Build a simple Spring Boot microservice](../02-build-a-simple-spring-boot-microservice/README.md), create a specific `spring-cloud-microservice` application in your Azure Spring Cloud instance:
```bash
az spring-cloud app create -n spring-cloud-microservice
```
You can now build your "spring-cloud-microservice" project and send it to Azure Spring Cloud:
```bash
cd spring-cloud-microservice
./mvnw clean package -DskipTests
az spring-cloud app deploy -n spring-cloud-microservice --jar-path target/demo-0.0.1-SNAPSHOT.jar
cd ..
```
## Test the project in the cloud
Go to [the Azure portal](https://portal.azure.com/?WT.mc_id=azurespringcloud-github-judubois):
- Look for your Azure Spring Cloud instance in your resource group
- Go to "Apps"
- Verify that `spring-cloud-microservice` has a `Registration status` of `1/1`. This shows that it is correctly registered in Spring Cloud Service Registry.
- Select `spring-cloud-microservice` to have more information on the microservice.
- Copy/paste the "Test Endpoint" that is provided.
You can now use cURL again to test the `/hello` endpoint, this time it is served by Azure Spring Cloud and configured using the Spring Config Server from [04 - Configure a Spring Cloud Config server](../04-configure-a-spring-cloud-config-server/README.md).
As a result, requesting the `/hello` endpoint should return the message that we configured in the `application.yml` file, coming from the Spring Cloud Config Server:
```bash
Configured by Azure Spring Cloud
```
## Stream application logs
When you run an application on your machine, you can see its output in the console. When you run a microservice on Azure Spring Cloud, you can also see its console output through Azure CLI:
```bash
az spring-cloud app logs --name spring-cloud-microservice -f
```
_Please be aware it might take a couple of minutes for the logs to show up._
You should see the console output of `spring-cloud-microservice` scroll by on your terminal:
![Console output](media/02-console-output.png)
Press CTRL+C to stop following the output and return to the shell.
## Query application logs
Streaming the console output as we just did may be helpful in understanding the immediate state of a microservice. However, sometimes it's necessary to look further into the past or to look for something specific. This is easily done with Log Analytics. In section 3, we enabled log aggregation in Azure Log Analytics. Such settings changes can take 1-2 minutes to apply, so by now, you should be able to query Azure Log Analytics.
[Open Azure Portal](https://portal.azure.com/?WT.mc_id=azurespringcloud-github-judubois) and navigate to your Azure Spring Cloud instance. Click on "Logs". This is a shortcut to the Log Analytics workspace that was created earlier. If a tutorial appears, feel free to skip it for now.
This workspace allows you to run queries on the aggregated logs. The most common query is to get the latest log from a specific application:
__Important:__ Spring Boot applications logs have a dedicated `AppPlatformLogsforSpring` type.
Here is how to get its 50 most recent logs of the `AppPlatformLogsforSpring` type for the microservice we just deployed:
Insert this text in the text area that states "Type your queries here or click on of the example queries to start". Click the text of the query, then click "Run".
```sql
AppPlatformLogsforSpring
| where AppName == "spring-cloud-microservice"
| project TimeGenerated, Log
| order by TimeGenerated desc
| limit 50
```
![Query logs](media/03-logs-query.png)
>💡 It can also take 1-2 minutes for the console output of an Azure Spring Cloud microservice to be read into Log Analytics.
## Conclusion
Congratulations, you have deployed a complete Spring Cloud microservice, using Spring Cloud Service Registry and Spring Cloud Config Server!
If you need to check your code, the final project is available in the ["spring-cloud-microservice" folder](spring-cloud-microservice/).
---
⬅️ Previous guide: [04 - Configure a Spring Cloud Config server](../04-configure-a-spring-cloud-config-server/README.md)
➡️ Next guide: [06 - Build a reactive Spring Boot microservice using Cosmos DB](../06-build-a-reactive-spring-boot-microservice-using-cosmosdb/README.md)

Просмотреть файл

@ -1,51 +1,53 @@
# 06 - Build a reactive Spring Boot microservice using Cosmos DB
# 06 - 使用Cosmos DB构建ReactiveSpring Boot微服务
__This guide is part of the [Azure Spring Cloud training](../README.md)__
**本教程是[Azure Spring Cloud 培训](../README.md)系列之一**
In this section, we'll build an application that uses a [Cosmos DB database](https://docs.microsoft.com/en-us/azure/cosmos-db/?WT.mc_id=azurespringcloud-github-judubois) in order to access a globally-distributed database with optimum performance.
We'll use the reactive programming paradigm to build our microservice in this section, leveraging the [Spring reactive stack](https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html). In contrast, we'll build a more traditional data-driven microservice in the next section.
在本节中,我们将构建一个使用[Cosmos DB](https://docs.microsoft.com/en-us/azure/cosmos-db/?WT.mc_id=azurespringcloud-github-judubois)的应用程序,以便访问性能最佳的全球分布式数据库。
我们将使用Reactive编程范式来构建本节中的微服务利用[Spring Reactive stack](https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html). 作为对比,我们将在下一节构建更传统的数据驱动微服务。
---
## Prepare the Cosmos DB database
## 准备Cosmos DB
From Section 00, you should already have a CosmosDB account named `sclabc-<unique string>`.
从第 00 节开始, 你应该已经有一个Cosmos DB帐户命名`sclabc-<unique string>`.
- Click on the "Data Explorer" menu item
- Expand the container named `azure-spring-cloud-cosmosdb`.
- In that container, expand the container named `City`.
- Click on "Items" and use the "New Item" button to create some sample items:
- 单击"数据资源管理器"菜单项
```json
{
"name": "Paris, France"
}
```
- 展开目录`azure-spring-cloud-cosmosdb`.
- 在该目录中,展开目录`City`.
- 单击"项目(Items)"并使用"新项目(New Item)"按钮创建一些示例项目:
```json
{
"name": "London, UK"
}
```
```json
{
"name": "Paris, France"
}
```
```json
{
"name": "London, UK"
}
```
![Data explorer](media/02-data-explorer.png)
## Create a Spring Webflux microservice
## 创建Spring Webflux微服务
The microservice that we create in this guide is [available here](city-service/).
我们在本教程中创建的微服务[可以参考在这里](city-service/).
To create our microservice, we will invoke the Spring Initalizer service from the command line:
为了创建我们的微服务我们将从命令行调用Spring Initalizer服务
```bash
curl https://start.spring.io/starter.tgz -d dependencies=webflux,cloud-eureka,cloud-config-client -d baseDir=city-service -d bootVersion=2.3.8 -d javaVersion=1.8 | tar -xzvf -
```
> We use the `Spring Webflux`, `Eureka Discovery Client` and the `Config Client` Spring Boot starters.
> 我们使用`Spring Webflux`,`Eureka Discovery Client`和`Config Client`Spring Boot starters。
## Add the Cosmos DB API
## 添加Cosmos DB API
In the application's `pom.xml` file, add the Cosmos DB dependency just after the `spring-cloud-starter-netflix-eureka-client` dependency:
在应用程序的`pom.xml`文件中,在`spring-cloud-starter-netflix-eureka-client`后添加Cosmos DB依赖
```xml
<dependency>
@ -55,9 +57,9 @@ In the application's `pom.xml` file, add the Cosmos DB dependency just after the
</dependency>
```
## Add Spring reactive code to get the data from the database
## 添加Spring Reactive代码从数据库获取数据
Next to the `DemoApplication` class, create a `City` domain object:
在的`DemoApplication`类目录下,创建一个`City` domain Object
```java
package com.example.demo;
@ -76,10 +78,10 @@ class City {
}
```
Then, in the same location, create a new `CityController.java` file that
contains the code that will be used to query the database.
然后,在同一位置创建一个新的`CityController.java`文件,
添加用于查询数据库的代码。
> The CityController class will get its Cosmos DB configuration from the Azure Spring Cloud service binding that we will configure later.
> City控制器类将从 Azure Spring Cloud服务绑定中获取其Cosmos DB 配置,我们将在稍后进行配置。
```java
package com.example.demo;
@ -131,32 +133,32 @@ public class CityController {
}
```
## Create the application on Azure Spring Cloud
## 在Azure Spring Cloud上创建应用程序
As in [02 - Build a simple Spring Boot microservice](../02-build-a-simple-spring-boot-microservice/README.md), create a specific `city-service` application in your Azure Spring Cloud instance:
如在[02 - 构建一个简单的Spring Boot微服务](../02-build-a-simple-spring-boot-microservice/README.md),创建一个特定的`city-service`应用在您的Azure Spring Cloud实例中
```bash
az spring-cloud app create -n city-service
```
## Bind the Cosmos DB database to the application
## 将Cosmos DB绑定到应用程序中
Azure Spring Cloud can automatically bind the Cosmos DB database we created to our microservice.
Azure Spring Cloud可以自动将我们创建的Cosmos DB绑定到我们的微服务中。
- Go to "Apps" in your Azure Spring Cloud instance.
- Select the `city-service` application
- Go to `Service bindings`
- Click on `Create service binding``
- Give your binding a name, for example `cosmosdb-city`
- Select the Cosmos DB account and database we created and keep the default `sql` API type
- In the drop-down list, select the primary master key
- Click on `Create` to create the database binding
- 转到 Azure Spring Cloud实例中的"应用"。
- 选择`city-service`应用
- 转到(G)`Service bindings`
- 单击"创建服务绑定"
- 例如,给绑定一个名称`cosmosdb-city`
- 选择我们创建的Cosmos DB帐户和数据库并保留默认值`sql`API 类型
- 在下拉列表中,选择主键
- 单击`Create`创建数据库绑定
![Bind Cosmos DB database](media/03-bind-service-cosmosdb.png)
## Deploy the application
## 部署应用程序
You can now build your "city-service" project and send it to Azure Spring Cloud:
现在,您可以构建您的"city-service"项目,并将其部署到 Azure Spring Cloud
```bash
cd city-service
@ -165,23 +167,23 @@ az spring-cloud app deploy -n city-service --jar-path target/demo-0.0.1-SNAPSHOT
cd ..
```
## Test the project in the cloud
## 在云中测试项目
- Go to "Apps" in your Azure Spring Cloud instance.
- Verify that `city-service` has a `Registration status` which says `1/1`. This shows that it is correctly registered in Spring Cloud Service Registry.
- Select `city-service` to have more information on the microservice.
- Copy/paste the "Test Endpoint" that is provided.
- 转到 Azure Spring Cloud实例中的"应用"。
- 验证`city-service`有一个`Registration status`其中说`1/1`.这表明它在Spring Cloud Service Registry注册成功。
- 选择`city-service`了解有关微服务的更多信息。
- 复制/粘贴提供的"测试终点"。
You can now use cURL to test the `/cities` endpoint, and it should give you the list of cities you created. For example, if you only created `Paris, France` and `London, UK` like it is shown in this guide, you should get:
您现在可以使用cURL来测试`/cities`终点,它应该返回你创建的城市列表。例如,如果您只创建`Paris, France`和`London, UK`就像本教程中显示的那样,您应该获得:
```json
[[{"name":"Paris, France"},{"name":"London, UK"}]]
```
If you need to check your code, the final project is available in the ["city-service" folder](city-service/).
如果您需要检查您的代码,最终项目可在["city-service"文件夹](city-service/).
---
⬅️ Previous guide: [05 - Build a Spring Boot microservice using Spring Cloud features](../05-build-a-spring-boot-microservice-using-spring-cloud-features/README.md)
⬅️上一个教程:[05 - 使用Spring Cloud功能构建Spring Boot微服务](../05-build-a-spring-boot-microservice-using-spring-cloud-features/README.md)
➡️ Next guide: [07 - Build a Spring Boot microservice using MySQL](../07-build-a-spring-boot-microservice-using-mysql/README.md)
➡️下一个教程:[07 - 使用 MySQL 构建Spring Boot微服务](../07-build-a-spring-boot-microservice-using-mysql/README.md)

Просмотреть файл

@ -0,0 +1,187 @@
# 06 - Build a reactive Spring Boot microservice using Cosmos DB
__This guide is part of the [Azure Spring Cloud training](../README.md)__
In this section, we'll build an application that uses a [Cosmos DB database](https://docs.microsoft.com/en-us/azure/cosmos-db/?WT.mc_id=azurespringcloud-github-judubois) in order to access a globally-distributed database with optimum performance.
We'll use the reactive programming paradigm to build our microservice in this section, leveraging the [Spring reactive stack](https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html). In contrast, we'll build a more traditional data-driven microservice in the next section.
---
## Prepare the Cosmos DB database
From Section 00, you should already have a CosmosDB account named `sclabc-<unique string>`.
- Click on the "Data Explorer" menu item
- Expand the container named `azure-spring-cloud-cosmosdb`.
- In that container, expand the container named `City`.
- Click on "Items" and use the "New Item" button to create some sample items:
```json
{
"name": "Paris, France"
}
```
```json
{
"name": "London, UK"
}
```
![Data explorer](media/02-data-explorer.png)
## Create a Spring Webflux microservice
The microservice that we create in this guide is [available here](city-service/).
To create our microservice, we will invoke the Spring Initalizer service from the command line:
```bash
curl https://start.spring.io/starter.tgz -d dependencies=webflux,cloud-eureka,cloud-config-client -d baseDir=city-service -d bootVersion=2.3.8 -d javaVersion=1.8 | tar -xzvf -
```
> We use the `Spring Webflux`, `Eureka Discovery Client` and the `Config Client` Spring Boot starters.
## Add the Cosmos DB API
In the application's `pom.xml` file, add the Cosmos DB dependency just after the `spring-cloud-starter-netflix-eureka-client` dependency:
```xml
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-cosmos</artifactId>
<version>4.5.0</version>
</dependency>
```
## Add Spring reactive code to get the data from the database
Next to the `DemoApplication` class, create a `City` domain object:
```java
package com.example.demo;
class City {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
```
Then, in the same location, create a new `CityController.java` file that
contains the code that will be used to query the database.
> The CityController class will get its Cosmos DB configuration from the Azure Spring Cloud service binding that we will configure later.
```java
package com.example.demo;
import com.azure.cosmos.CosmosAsyncContainer;
import com.azure.cosmos.CosmosClientBuilder;
import com.azure.cosmos.models.CosmosQueryRequestOptions;
import com.azure.cosmos.models.FeedResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import javax.annotation.PostConstruct;
import java.util.List;
@RestController
public class CityController {
@Value("${azure.cosmosdb.uri}")
private String cosmosDbUrl;
@Value("${azure.cosmosdb.key}")
private String cosmosDbKey;
@Value("${azure.cosmosdb.database}")
private String cosmosDbDatabase;
private CosmosAsyncContainer container;
@PostConstruct
public void init() {
container = new CosmosClientBuilder()
.endpoint(cosmosDbUrl)
.key(cosmosDbKey)
.buildAsyncClient()
.getDatabase(cosmosDbDatabase)
.getContainer("City");
}
@GetMapping("/cities")
public Flux<List<City>> getCities() {
CosmosQueryRequestOptions options = new CosmosQueryRequestOptions();
return container.queryItems("SELECT TOP 20 * FROM City c", options, City.class)
.byPage()
.map(FeedResponse::getResults);
}
}
```
## Create the application on Azure Spring Cloud
As in [02 - Build a simple Spring Boot microservice](../02-build-a-simple-spring-boot-microservice/README.md), create a specific `city-service` application in your Azure Spring Cloud instance:
```bash
az spring-cloud app create -n city-service
```
## Bind the Cosmos DB database to the application
Azure Spring Cloud can automatically bind the Cosmos DB database we created to our microservice.
- Go to "Apps" in your Azure Spring Cloud instance.
- Select the `city-service` application
- Go to `Service bindings`
- Click on `Create service binding``
- Give your binding a name, for example `cosmosdb-city`
- Select the Cosmos DB account and database we created and keep the default `sql` API type
- In the drop-down list, select the primary master key
- Click on `Create` to create the database binding
![Bind Cosmos DB database](media/03-bind-service-cosmosdb.png)
## Deploy the application
You can now build your "city-service" project and send it to Azure Spring Cloud:
```bash
cd city-service
./mvnw clean package -DskipTests
az spring-cloud app deploy -n city-service --jar-path target/demo-0.0.1-SNAPSHOT.jar
cd ..
```
## Test the project in the cloud
- Go to "Apps" in your Azure Spring Cloud instance.
- Verify that `city-service` has a `Registration status` which says `1/1`. This shows that it is correctly registered in Spring Cloud Service Registry.
- Select `city-service` to have more information on the microservice.
- Copy/paste the "Test Endpoint" that is provided.
You can now use cURL to test the `/cities` endpoint, and it should give you the list of cities you created. For example, if you only created `Paris, France` and `London, UK` like it is shown in this guide, you should get:
```json
[[{"name":"Paris, France"},{"name":"London, UK"}]]
```
If you need to check your code, the final project is available in the ["city-service" folder](city-service/).
---
⬅️ Previous guide: [05 - Build a Spring Boot microservice using Spring Cloud features](../05-build-a-spring-boot-microservice-using-spring-cloud-features/README.md)
➡️ Next guide: [07 - Build a Spring Boot microservice using MySQL](../07-build-a-spring-boot-microservice-using-mysql/README.md)

Просмотреть файл

@ -1,31 +1,31 @@
# 07 - Build a Spring Boot microservice using MySQL
# 07 - 使用 MySQL 构建Spring Boot微服务
__This guide is part of the [Azure Spring Cloud training](../README.md)__
**本教程是[Azure Spring Cloud 培训](../README.md)系列之一**
In this section, we'll build another data-driven microservice. This time, we will use a relational database, a [MySQL database managed by Azure](https://docs.microsoft.com/en-us/azure/mysql/?WT.mc_id=azurespringcloud-github-judubois). And we'll use Java Persistence API (JPA) to access the data in a way that is more frequently used in the Java ecosystem.
在此部分中,我们将构建另一个数据驱动的微服务。这一次,我们将使用一个关系数据库,一个[由Azure管理的 MySQL 数据库](https://docs.microsoft.com/en-us/azure/mysql/?WT.mc_id=azurespringcloud-github-judubois).我们将使用 Java 持久性 API JPA 来访问数据这是也Java 生态里主流的方式。
---
## Create the application on Azure Spring Cloud
## 在Azure Spring Cloud上创建应用程序
As in [02 - Build a simple Spring Boot microservice](../02-build-a-simple-spring-boot-microservice/README.md), create a specific `weather-service` application in your Azure Spring Cloud instance:
如在[02 - 构建一个简单的Spring Boot微服务](../02-build-a-simple-spring-boot-microservice/README.md),创建一个特定的`weather-service`应用在您的Azure Spring Cloud实例中
```bash
az spring-cloud app create -n weather-service
```
## 配置 MySQL 服务器实例
## Configure the MySQL Server instance
在遵循第 00 节中的步骤后,您应该有一个名为 MySQL 实例的 Azure 数据库`sclabm-<unique string>`在您的资源组中。
After following the steps in Section 00, you should have an Azure Database for MySQL instance named `sclabm-<unique string>` in your resource group.
然而,在我们使用它之前,我们需要执行几个任务:
Before we can use it however, we will need to perform several tasks:
1. 创建 MySQL 防火墙规则,以便从我们的本地环境中进行连接。
2. 创建 MySQL 防火墙规则,允许来自 Azure 服务的连接。这将启用来自Azure Spring Cloud的连接。
3. 创建一个MySQL数据库。
1. Create a MySQL firewall rule to allow connections from our local environment.
1. Create a MySQL firewall rule to allow connections from Azure Services. This will enable connections from Azure Spring Cloud.
1. Create a MySQL database.
> 💡When prompted for a password, enter the MySQL password you specified when deploying the ARM template in [Section 00](../00-setup-your-environment/README.md).
> 💡当提示密码时,输入您在部署 ARM 模板时指定的 MySQL 密码[第 00 节](../00-setup-your-environment/README.md).
```bash
# Obtain the info on the MYSQL server in our resource group:
@ -59,37 +59,37 @@ echo "Your MySQL username is: ${MYSQL_USERNAME}"
```
## Bind the MySQL database to the application
## 将 MySQL 数据库绑定到应用程序
As we did for CosmosDB in the previous section, create a service binding for the MySQL database to make it available to Azure Spring Cloud microservices.
In the [Azure Portal](https://portal.azure.com/?WT.mc_id=azurespringcloud-github-judubois):
正如我们在上一节中为Cosmos DB所做的那样为 MySQL 数据库创建一个绑定服务,使其可用于 Azure Spring Cloud微服务。
在[Azure门户](https://portal.azure.com/?WT.mc_id=azurespringcloud-github-judubois):
- Navigate to your Azure Spring Cloud instance
- Click on Apps
- Click on `weather-service`.
- Click on "Service Bindings" and then on "Create Service Binding".
- Populate the service binding fields as shown.
- The username will be displayed in last line of output from the section above.
- The password is the one you specified in section 0. The default value is `super$ecr3t`.
- Click on `Create` to create the database binding
- 导航到您的Azure Spring Cloud实例
- 单击应用
- 单击`weather-service`.
- 单击"服务绑定",然后点击"创建服务绑定"。
- 如图所示填充服务绑定字段。
- 用户名将显示在上面部分的最后一行输出中。
- 密码是您在第 0 节中指定的密码。默认值为`super$ecr3t`.
- 单击`Create`创建数据库绑定
![MySQL Service Binding](media/01-create-service-binding-mysql.png)
## Create a Spring Boot microservice
## 创建Spring Boot微服务
Now that we've provisioned the Azure Spring Cloud instance and configured the service binding, let's get the code for `weather-service` ready. The microservice that we create in this guide is [available here](weather-service/).
现在我们已经准备了Azure Spring Cloud实例并配置了服务绑定让我们获取代码`weather-service`准备。我们在本教程中创建的微服务[可参考这里](weather-service/).
To create our microservice, we will invoke the Spring Initalizer service from the command line:
为了创建我们的微服务我们将从命令行调用Spring Initalizer服务
```bash
curl https://start.spring.io/starter.tgz -d dependencies=web,data-jpa,mysql,cloud-eureka,cloud-config-client -d baseDir=weather-service -d bootVersion=2.3.8 -d javaVersion=1.8 | tar -xzvf -
```
> We use the `Spring Web`, `Spring Data JPA`, `MySQL Driver`, `Eureka Discovery Client` and the `Config Client` components.
> 我们使用`Spring Web`,`Spring Data JPA`,`MySQL Driver`,`Eureka Discovery Client`和`Config Client`组件。
## Add Spring code to get the data from the database
## 添加Spring代码从数据库获取数据
Next to the `DemoApplication` class, create a `Weather` JPA entity:
在`DemoApplication`类同一目录下,创建一个名为`Weather` 的JPA 实体:
```java
package com.example.demo;
@ -133,7 +133,7 @@ public class Weather {
}
```
Then, create a Spring Data repository to manage this entity, called `WeatherRepository`:
然后创建一个Spring Data Repository来管理此实体称为`WeatherRepository`:
```java
package com.example.demo;
@ -144,7 +144,7 @@ public interface WeatherRepository extends CrudRepository<Weather, String> {
}
```
And finish coding this application by adding a Spring MVC controller called `WeatherController`:
并完成编码此应用程序添加一个Spring MVC控制器为`WeatherController`:
```java
package com.example.demo;
@ -169,26 +169,26 @@ public class WeatherController {
}
```
## Add sample data in MySQL
## 在 MySQL 中添加样本数据
In order to have Hibernate automatically create your database, open up the `src/main/resources/application.properties` file and add:
为了让Hibernate自动创建您的数据库打开`src/main/resources/application.properties`文件并添加:
```properties
spring.jpa.hibernate.ddl-auto=create
```
Then, in order to have Spring Boot add sample data at startup, create a `src/main/resources/import.sql` file and add:
然后为了让Spring Boot在启动时添加示例数据创建`src/main/resources/import.sql`文件并添加:
```sql
INSERT INTO `azure-spring-cloud-training`.`weather` (`city`, `description`, `icon`) VALUES ('Paris, France', 'Very cloudy!', 'weather-fog');
INSERT INTO `azure-spring-cloud-training`.`weather` (`city`, `description`, `icon`) VALUES ('London, UK', 'Quite cloudy', 'weather-pouring');
```
> The icons we are using are the ones from [https://materialdesignicons.com/](https://materialdesignicons.com/) - you can pick their other weather icons if you wish.
> 我们正在使用的图标是从<https://materialdesignicons.com/>获得-如果你愿意,你可以选择他们的其他天气图标。
## Deploy the application
## 部署应用程序
You can now build your "weather-service" project and send it to Azure Spring Cloud:
您现在可以构建您的"天气服务"项目,并将其发送到 Azure Spring Cloud
```bash
cd weather-service
@ -197,23 +197,23 @@ az spring-cloud app deploy -n weather-service --jar-path target/demo-0.0.1-SNAPS
cd ..
```
## Test the project in the cloud
## 在云中测试项目
- Go to "Apps" in your Azure Spring Cloud instance.
- Verify that `weather-service` has a `Registration status` which says `1/1`. This shows that it is correctly registered in the Spring Cloud Service Registry.
- Select `weather-service` to have more information on the microservice.
- Copy/paste the "Test Endpoint" that is provided. You might have to click on `See more` to find it.
- 转到 Azure Spring Cloud实例中的"应用"。
- 验证`weather-service`有一个`Registration status`其中说`1/1`.这表明它在Spring Cloud Service Registry注册成功。
- 选择`weather-service` 查看有关微服务的更多信息。
- 复制/粘贴提供的"测试终点"。您可能需要单击`See more`才能看到。
You can now use cURL to test the `/weather/city` endpoint. For example, to test for `Paris, France` city, append to the end of the test endpoint: `/weather/city?name=Paris%2C%20France`.
您现在可以使用cURL来测试`/weather/city`端点。例如,测试`Paris, France`城市,附加到测试终点的末尾:`/weather/city?name=Paris%2C%20France`.
```json
{"city":"Paris, France","description":"Very cloudy!","icon":"weather-fog"}
```
If you need to check your code, the final project is available in the ["weather-service" folder](weather-service/).
如果您需要参考代码,最终完成的项目可在["weather-service"文件夹](weather-service/).
---
⬅️ Previous guide: [06 - Build a reactive Spring Boot microservice using Cosmos DB](../06-build-a-reactive-spring-boot-microservice-using-cosmosdb/README.md)
⬅️上一个教程:[06 - 使用Cosmos DB构建Reactive Spring Boot微服务](../06-build-a-reactive-spring-boot-microservice-using-cosmosdb/README.md)
➡️ Next guide: [08 - Build a Spring Cloud Gateway](../08-build-a-spring-cloud-gateway/README.md)
➡️下一个教程:[08 - 构建Spring Cloud网关](../08-build-a-spring-cloud-gateway/README.md)

Просмотреть файл

@ -0,0 +1,219 @@
# 07 - Build a Spring Boot microservice using MySQL
__This guide is part of the [Azure Spring Cloud training](../README.md)__
In this section, we'll build another data-driven microservice. This time, we will use a relational database, a [MySQL database managed by Azure](https://docs.microsoft.com/en-us/azure/mysql/?WT.mc_id=azurespringcloud-github-judubois). And we'll use Java Persistence API (JPA) to access the data in a way that is more frequently used in the Java ecosystem.
---
## Create the application on Azure Spring Cloud
As in [02 - Build a simple Spring Boot microservice](../02-build-a-simple-spring-boot-microservice/README.md), create a specific `weather-service` application in your Azure Spring Cloud instance:
```bash
az spring-cloud app create -n weather-service
```
## Configure the MySQL Server instance
After following the steps in Section 00, you should have an Azure Database for MySQL instance named `sclabm-<unique string>` in your resource group.
Before we can use it however, we will need to perform several tasks:
1. Create a MySQL firewall rule to allow connections from our local environment.
1. Create a MySQL firewall rule to allow connections from Azure Services. This will enable connections from Azure Spring Cloud.
1. Create a MySQL database.
> 💡When prompted for a password, enter the MySQL password you specified when deploying the ARM template in [Section 00](../00-setup-your-environment/README.md).
```bash
# Obtain the info on the MYSQL server in our resource group:
MYSQL_INFO=$(az mysql server list --query '[0]')
MYSQL_SERVERNAME=$(az mysql server list --query '[0].name' -o tsv)
MYSQL_USERNAME="$(az mysql server list --query '[0].administratorLogin' -o tsv)@${MYSQL_SERVERNAME}"
MYSQL_HOST="$(az mysql server list --query '[0].fullyQualifiedDomainName' -o tsv)"
# Create a firewall rule to allow connections from your machine:
MY_IP=$(curl whatismyip.akamai.com 2>/dev/null)
az mysql server firewall-rule create \
--server-name $MYSQL_SERVERNAME \
--name "connect-from-lab" \
--start-ip-address "$MY_IP" \
--end-ip-address "$MY_IP"
# Create a firewall rule to allow connections from Azure services:
az mysql server firewall-rule create \
--server-name $MYSQL_SERVERNAME \
--name "connect-from-azure" \
--start-ip-address "0.0.0.0" \
--end-ip-address "0.0.0.0"
# Create a MySQL database
az mysql db create \
--name "azure-spring-cloud-training" \
--server-name $MYSQL_SERVERNAME
# Display MySQL username (to be used in the next section)
echo "Your MySQL username is: ${MYSQL_USERNAME}"
```
## Bind the MySQL database to the application
As we did for CosmosDB in the previous section, create a service binding for the MySQL database to make it available to Azure Spring Cloud microservices.
In the [Azure Portal](https://portal.azure.com/?WT.mc_id=azurespringcloud-github-judubois):
- Navigate to your Azure Spring Cloud instance
- Click on Apps
- Click on `weather-service`.
- Click on "Service Bindings" and then on "Create Service Binding".
- Populate the service binding fields as shown.
- The username will be displayed in last line of output from the section above.
- The password is the one you specified in section 0. The default value is `super$ecr3t`.
- Click on `Create` to create the database binding
![MySQL Service Binding](media/01-create-service-binding-mysql.png)
## Create a Spring Boot microservice
Now that we've provisioned the Azure Spring Cloud instance and configured the service binding, let's get the code for `weather-service` ready. The microservice that we create in this guide is [available here](weather-service/).
To create our microservice, we will invoke the Spring Initalizer service from the command line:
```bash
curl https://start.spring.io/starter.tgz -d dependencies=web,data-jpa,mysql,cloud-eureka,cloud-config-client -d baseDir=weather-service -d bootVersion=2.3.8 -d javaVersion=1.8 | tar -xzvf -
```
> We use the `Spring Web`, `Spring Data JPA`, `MySQL Driver`, `Eureka Discovery Client` and the `Config Client` components.
## Add Spring code to get the data from the database
Next to the `DemoApplication` class, create a `Weather` JPA entity:
```java
package com.example.demo;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Weather {
@Id
private String city;
private String description;
private String icon;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
}
```
Then, create a Spring Data repository to manage this entity, called `WeatherRepository`:
```java
package com.example.demo;
import org.springframework.data.repository.CrudRepository;
public interface WeatherRepository extends CrudRepository<Weather, String> {
}
```
And finish coding this application by adding a Spring MVC controller called `WeatherController`:
```java
package com.example.demo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping(path="/weather")
public class WeatherController {
private final WeatherRepository weatherRepository;
public WeatherController(WeatherRepository weatherRepository) {
this.weatherRepository = weatherRepository;
}
@GetMapping("/city")
public @ResponseBody Weather getWeatherForCity(@RequestParam("name") String cityName) {
return weatherRepository.findById(cityName).get();
}
}
```
## Add sample data in MySQL
In order to have Hibernate automatically create your database, open up the `src/main/resources/application.properties` file and add:
```properties
spring.jpa.hibernate.ddl-auto=create
```
Then, in order to have Spring Boot add sample data at startup, create a `src/main/resources/import.sql` file and add:
```sql
INSERT INTO `azure-spring-cloud-training`.`weather` (`city`, `description`, `icon`) VALUES ('Paris, France', 'Very cloudy!', 'weather-fog');
INSERT INTO `azure-spring-cloud-training`.`weather` (`city`, `description`, `icon`) VALUES ('London, UK', 'Quite cloudy', 'weather-pouring');
```
> The icons we are using are the ones from [https://materialdesignicons.com/](https://materialdesignicons.com/) - you can pick their other weather icons if you wish.
## Deploy the application
You can now build your "weather-service" project and send it to Azure Spring Cloud:
```bash
cd weather-service
./mvnw clean package -DskipTests
az spring-cloud app deploy -n weather-service --jar-path target/demo-0.0.1-SNAPSHOT.jar
cd ..
```
## Test the project in the cloud
- Go to "Apps" in your Azure Spring Cloud instance.
- Verify that `weather-service` has a `Registration status` which says `1/1`. This shows that it is correctly registered in the Spring Cloud Service Registry.
- Select `weather-service` to have more information on the microservice.
- Copy/paste the "Test Endpoint" that is provided. You might have to click on `See more` to find it.
You can now use cURL to test the `/weather/city` endpoint. For example, to test for `Paris, France` city, append to the end of the test endpoint: `/weather/city?name=Paris%2C%20France`.
```json
{"city":"Paris, France","description":"Very cloudy!","icon":"weather-fog"}
```
If you need to check your code, the final project is available in the ["weather-service" folder](weather-service/).
---
⬅️ Previous guide: [06 - Build a reactive Spring Boot microservice using Cosmos DB](../06-build-a-reactive-spring-boot-microservice-using-cosmosdb/README.md)
➡️ Next guide: [08 - Build a Spring Cloud Gateway](../08-build-a-spring-cloud-gateway/README.md)

Просмотреть файл

@ -1,26 +1,27 @@
# 08 - Build a Spring Cloud Gateway
# 08 - 构建Spring Cloud网关
__This guide is part of the [Azure Spring Cloud training](../README.md)__
**本教程是[Azure Spring Cloud 培训](../README.md)系列之一**
A Spring Cloud gateway allows you to selectively expose your microservices and to route traffic to them and among them. In this section, we will create a Spring Cloud Gateway that will expose the microservices we created in the preceding two sections.
Spring Cloud网关允许您有选择地暴露您的微服务并将流量路由到它们之间。在此部分中我们将创建一个"Spring Cloud Gateway",该网关将使用我们在前两个部分创建的微服务。
---
## Create a Spring Cloud Gateway
## 创建Spring Cloud网关
The application that we create in this guide is [available here](gateway/).
我们在本教程中创建的应用程序[可参考这里](gateway/).
To create our gateway, we will invoke the Spring Initalizer service from the command line:
为了创建我们的网关我们将从命令行调用Spring Initalizer服务
```bash
curl https://start.spring.io/starter.tgz -d dependencies=cloud-gateway,cloud-eureka,cloud-config-client -d baseDir=gateway -d bootVersion=2.3.8 -d javaVersion=1.8 | tar -xzvf -
```
> We use the `Cloud Gateway`, `Eureka Discovery Client` and the `Config Client` components.
> 我们使用`Cloud Gateway`,`Eureka Discovery Client`和`Config Client`组件。
## Configure the application
## 配置应用程序
Rename `src/main/resources/application.properties` to `src/main/resources/application.yml` and add the following configuration:
重命名`src/main/resources/application.properties`自`src/main/resources/application.yml`并添加以下配置:
```yaml
spring:
@ -40,21 +41,21 @@ spring:
```
- The `spring.main.allow-bean-definition-overriding=true` part is to configure Spring Cloud Gateway to use the Spring Cloud Discovery Server bean configured in the Azure Spring Cloud Client library.
- The `spring.cloud.gateway.discovery.locator.enabled=true` part is to configure Spring Cloud Gateway to use the Spring Cloud Service Registry to discover the available microservices.
- The `spring.cloud.gateway.globalcors.corsConfiguration` part is to allow CORS requests to our gateway. This will be helpful in the next guide, when we will add a front-end that is not hosted on Azure Spring Cloud.
- `spring.main.allow-bean-definition-overriding=true`这部分是配置Spring Cloud网关以使用 Azure Spring Cloud Client Library中配置的Spring Cloud Discovery Server bean。
- `spring.cloud.gateway.discovery.locator.enabled=true`这部分是配置Spring Cloud网关使用Spring Cloud Service Registry发现可用的微服务。
- `spring.cloud.gateway.globalcors.corsConfiguration`这部分是允许CORS请求到我们的网关。这将在下一个教程中使用到届时我们将添加未在 Azure Spring 云上托管的前端应用。
## Create the application on Azure Spring Cloud
## 在Azure Spring Cloud上创建应用程序
As in [02 - Build a simple Spring Boot microservice](../02-build-a-simple-spring-boot-microservice/README.md), create a specific `gateway` application in your Azure Spring Cloud instance. As this application is a gateway, we add the `--is-public true` flag so it is exposed publicly.
如在[02 - 构建一个简单的Spring Boot微服务](../02-build-a-simple-spring-boot-microservice/README.md),创建一个特定的`gateway`应用在您的Azure Spring Cloud实例中。由于此应用程序是网关我们添加`--is-public true`标志,所以它是互联网可访问的。
```bash
az spring-cloud app create -n gateway --is-public true
```
## Deploy the application
## 部署应用程序
You can now build your "gateway" project and send it to Azure Spring Cloud:
您现在可以构建您的"Gateway"项目并将其部署到 Azure Spring Cloud 中:
```bash
cd gateway
@ -64,23 +65,23 @@ cd ..
```
## Test the project in the cloud
## 在云中测试项目
- Go to "Apps" in your Azure Spring Cloud instance.
- Verify that `gateway` has a `Registration status` which says `1/1`. This shows that it is correctly registered in the Spring Cloud Service Registry.
- Select `gateway` to have more information on the microservice.
- Copy/paste the public URL that is provided (there is a "Test Endpoint" like for microservices, but the gateway is directly exposed on the Internet, so let's use the public URL). Keep this URL handy for subsequent sections.
- 转到 Azure Spring Cloud实例中的"应用"。
- 验证`gateway`有一个`Registration status`其中说`1/1`.这表明它在Spring Cloud Service Registry注册成功。
- 选择`gateway`了解有关微服务的更多信息。
- 复制/粘贴提供的公共网址(有一个"测试端点"如微服务但网关直接暴露在互联网上所以我们可以使用公共网址。为后续部分方便测试记下这个URL。
As the gateway is connected to the Spring Cloud Service Registry, it should have automatically opened routes to the available microservices, with URL paths in the form of `/MICROSERVICE-ID/**`:
[The MICROSERVICE-ID must be in capital letters]
由于网关连接到Spring Cloud Service Registry因此它应该自动打开通往可用微服务的路由URL 路径的格式如下`/MICROSERVICE-ID/**`:
[MICROSERVICE-ID必须是大写字母]
- Test the `city-service` microservice endpoint by doing: `curl https://XXXXXXXX-gateway.azuremicroservices.io/CITY-SERVICE/cities` (replacing XXXXXXXX with the name of your Azure Spring Cloud instance)
- Test the `weather-service` microservice endpoint by doing: `curl 'https://XXXXXXXX-gateway.azuremicroservices.io/WEATHER-SERVICE/weather/city?name=Paris%2C%20France'` (replacing XXXXXXXX by the name of your gateway)
- 测试`city-service`微服务终点通过做:`curl https://XXXXXXXX-gateway.azuremicroservices.io/CITY-SERVICE/cities`用您的Azure Spring Cloud实例名称替换X
- 测试`weather-service`微服务终点通过做:`curl 'https://XXXXXXXX-gateway.azuremicroservices.io/WEATHER-SERVICE/weather/city?name=Paris%2C%20France'`用网关名称替换X
If you need to check your code, the final project is available in the ["gateway" folder](gateway/).
如果您需要参考您的代码,最终项目在["gateway"文件夹](gateway/).
---
⬅️ Previous guide: [07 - Build a Spring Boot microservice using MySQL](../07-build-a-spring-boot-microservice-using-mysql/README.md)
⬅️上一个教程:[07 - 使用 MySQL 构建Spring Boot微服务](../07-build-a-spring-boot-microservice-using-mysql/README.md)
➡️ Next guide: [09 - Putting it all together, a complete microservice stack](../09-putting-it-all-together-a-complete-microservice-stack/README.md)
➡️下一个教程:[09 - 综上所述一个完整的微服务Stack](../09-putting-it-all-together-a-complete-microservice-stack/README.md)

Просмотреть файл

@ -0,0 +1,86 @@
# 08 - Build a Spring Cloud Gateway
__This guide is part of the [Azure Spring Cloud training](../README.md)__
A Spring Cloud gateway allows you to selectively expose your microservices and to route traffic to them and among them. In this section, we will create a Spring Cloud Gateway that will expose the microservices we created in the preceding two sections.
---
## Create a Spring Cloud Gateway
The application that we create in this guide is [available here](gateway/).
To create our gateway, we will invoke the Spring Initalizer service from the command line:
```bash
curl https://start.spring.io/starter.tgz -d dependencies=cloud-gateway,cloud-eureka,cloud-config-client -d baseDir=gateway -d bootVersion=2.3.8 -d javaVersion=1.8 | tar -xzvf -
```
> We use the `Cloud Gateway`, `Eureka Discovery Client` and the `Config Client` components.
## Configure the application
Rename `src/main/resources/application.properties` to `src/main/resources/application.yml` and add the following configuration:
```yaml
spring:
main:
allow-bean-definition-overriding: true
cloud:
gateway:
discovery:
locator:
enabled: true
globalcors:
corsConfigurations:
'[/**]':
allowedOrigins: "*"
allowedMethods:
- GET
```
- The `spring.main.allow-bean-definition-overriding=true` part is to configure Spring Cloud Gateway to use the Spring Cloud Discovery Server bean configured in the Azure Spring Cloud Client library.
- The `spring.cloud.gateway.discovery.locator.enabled=true` part is to configure Spring Cloud Gateway to use the Spring Cloud Service Registry to discover the available microservices.
- The `spring.cloud.gateway.globalcors.corsConfiguration` part is to allow CORS requests to our gateway. This will be helpful in the next guide, when we will add a front-end that is not hosted on Azure Spring Cloud.
## Create the application on Azure Spring Cloud
As in [02 - Build a simple Spring Boot microservice](../02-build-a-simple-spring-boot-microservice/README.md), create a specific `gateway` application in your Azure Spring Cloud instance. As this application is a gateway, we add the `--is-public true` flag so it is exposed publicly.
```bash
az spring-cloud app create -n gateway --is-public true
```
## Deploy the application
You can now build your "gateway" project and send it to Azure Spring Cloud:
```bash
cd gateway
./mvnw clean package -DskipTests
az spring-cloud app deploy -n gateway --jar-path target/demo-0.0.1-SNAPSHOT.jar
cd ..
```
## Test the project in the cloud
- Go to "Apps" in your Azure Spring Cloud instance.
- Verify that `gateway` has a `Registration status` which says `1/1`. This shows that it is correctly registered in the Spring Cloud Service Registry.
- Select `gateway` to have more information on the microservice.
- Copy/paste the public URL that is provided (there is a "Test Endpoint" like for microservices, but the gateway is directly exposed on the Internet, so let's use the public URL). Keep this URL handy for subsequent sections.
As the gateway is connected to the Spring Cloud Service Registry, it should have automatically opened routes to the available microservices, with URL paths in the form of `/MICROSERVICE-ID/**`:
[The MICROSERVICE-ID must be in capital letters]
- Test the `city-service` microservice endpoint by doing: `curl https://XXXXXXXX-gateway.azuremicroservices.io/CITY-SERVICE/cities` (replacing XXXXXXXX with the name of your Azure Spring Cloud instance)
- Test the `weather-service` microservice endpoint by doing: `curl 'https://XXXXXXXX-gateway.azuremicroservices.io/WEATHER-SERVICE/weather/city?name=Paris%2C%20France'` (replacing XXXXXXXX by the name of your gateway)
If you need to check your code, the final project is available in the ["gateway" folder](gateway/).
---
⬅️ Previous guide: [07 - Build a Spring Boot microservice using MySQL](../07-build-a-spring-boot-microservice-using-mysql/README.md)
➡️ Next guide: [09 - Putting it all together, a complete microservice stack](../09-putting-it-all-together-a-complete-microservice-stack/README.md)

Просмотреть файл

@ -1,72 +1,73 @@
# 09 - Putting it all together, a complete microservice stack
# 09 - 综上所述一个完整的微服务Stack
__This guide is part of the [Azure Spring Cloud training](../README.md)__
**本教程是[Azure Spring Cloud 培训](../README.md)系列之一**
Now that we have made two microservices publicly available, we will incorporate a user interface to see them in action. Then, we will use Azure Monitor to monitor the flow of traffic to and among our services and to track metrics.
现在,我们已经公开了两个微服务,我们将添加一个用户界面,看看他们的实际效果。然后,我们将使用 Azure Monitor 监控访问我们服务以及服务之间的流量,并跟踪指标。
---
## Add a front-end to the microservices stack
## 在微服务堆栈中添加前端
We now have a complete microservices stack:
我们现在有一个完整的微服务堆栈:
- A gateway based on Spring Cloud Gateway.
- A reactive `city-service` microservice, that stores its data on Cosmos DB.
- A `weather-service` microservice, that stores its data on MySQL
- 基于Spring Cloud Gateway的网关。
- Reactive`city-service`微服务将其数据存储在Cosmos DB上。
- `weather-service`微服务将其数据存储在MySQL上
In order to finish this architecture, we need to add a front-end to it:
为了完成此架构,我们需要添加一个前端:
- We've already built a VueJS application, that is available in the ["weather-app" folder](weather-app/).
- This front-end could be hosted in Azure Spring Cloud, using the same domain name (this won't be the case in this guide, and that's why we enabled CORS in our gateway earlier).
- If you are familiar with NodeJS and Vue CLI, you can run this application locally by typing `npm install && vue ui`.
- 我们已经建立了一个VueJS应用程序参考["weather-app"文件夹](weather-app/).
- 此前端可以使用相同的域名托管在 Azure Spring Cloud中本教程中并非如此这就是为什么我们之前在网关中启用了 CORS 的原因)。
- 如果您熟悉 NodeJS 和 Vue CLI则可以通过命令行在本地运行此命令`npm install && vue ui`.
In order to simplify this part, which is not relevant to understanding Spring Cloud, we have already built a running front-end:
这与了解Spring Cloud无关为了简化这部分我们已经建立了一个运行前端
__[https://spring-training.azureedge.net/](https://spring-training.azureedge.net/)__
**<https://spring-training.azureedge.net/>**
For your information, this website is hosted on Azure Storage and served through Azure CDN for optimum performance.
该网站在 Azure 存储上托管,并通过 Azure CDN 提供服务,以获得最佳性能。
Go to [https://spring-training.azureedge.net/](https://spring-training.azureedge.net/), input your Spring Cloud Gateway's public URL in the text field and click on "Go". You should see the following screen:
使用流览器转到(G)<https://spring-training.azureedge.net/>在输入框中输入您的Spring Cloud网关的公共网址然后单击"Go"。您应该看到以下屏幕:
![VueJS front-end](media/01-vuejs-frontend.png)
## Review the distributed tracing to better understand the architecture
## 查看分布式跟踪以更好地了解架构
We have already enabled distributed tracing on our Azure Spring Cloud instance in Section 1 by adding the `--enable-java-agent` flag to the create command.
在第 1 节中,我们已经通过添加`--enable-java-agent`标记到创建Azure Spring Cloud实例的命令启用了分布式跟踪的功能。
Now, you can use the VueJS application on [https://spring-training.azureedge.net/](https://spring-training.azureedge.net/) to generate some traffic on the microservices stack.
现在,您可以在 VueJS 应用程序上使用<https://spring-training.azureedge.net/>在微服务堆栈上生成一些流量。
>💡 Tracing data can take a couple of minutes to be ingested by the system, so use this time to generate some load.
> 💡跟踪数据可能需要几分钟才能被系统采集到,因此请利用这段时间生成一些负载。
In the "Application Insights" menu in Azure Portal, you should now have access to a full application map, as well as a search engine that allows you to find performance bottlenecks.
在 Azure Portal 中的"应用洞察"菜单中,您现在应该可以访问完整的应用程序地图以及一些性能指标,让您找到性能瓶颈在哪。
![Distributed tracing](media/02-distributed-tracing.png)
> 💡 If your application map looks different from the one above, select the hierarchical view from the layout switch in the top-right corner:
> 💡 如果您的应用地图看起来与上图不同,请从右上角的布局开关中选择分层视图:
>
> ![layout switch](media/05-layout-switch.png)
## Review the performance metrics
## 查看性能指标
Open a more holistic view at the `Performance` blade where you can see response times and request counts for operations exposed by your applications.
在`Performance`标签,在那里你可以看到应用程序的响应时间和请求计数。
![Trace detail](media/03-trace-detail.png)
For even more detailed data, navigate to the `Dependencies` tab in the `Performance` blade where you can see all your dependencies and their response times and request counts.
有关更详细的数据,导航到`Dependencies`选项卡中的选项卡`Performance`标签,你可以看到你所有的依赖关系和他们的响应时间和请求计数。
## Scale applications
## 缩放应用
Now that distributed tracing is enabled, we can scale applications depending on our needs.
现在,已启用分布式跟踪,我们可以根据我们的需要对应用程序进行扩展。
- Go to [the Azure portal](https://portal.azure.com/?WT.mc_id=azurespringcloud-github-judubois).
- Go to the overview page of your Azure Spring Cloud server and select "Apps" in the menu.
- Select one service and click on "Scale Out" in the menu. Select the service that you want to scale out.
![Application scaling](media/04-scale-out.png)
- Modify the number of instances to manually scale the service. You can also set custom auto scaling based on metrics.
![Application scaling](media/04b-auto-scaling.png)
- 转到(G)[Azure门户网站](https://portal.azure.com/).
- 转到 Azure Spring Cloud服务器的概述页面并在菜单中选择"应用"。
- 选择一项服务,然后单击菜单中的"Scale Out"。选择要扩展的服务。
![Application scaling](media/04-scale-out.png)
- 修改实例数量以手动扩展服务。您还可以根据指标设置自定义自动缩放。
![Application scaling](media/04b-auto-scaling.png)
---
⬅️ Previous guide: [08 - Build a Spring Cloud Gateway](../08-build-a-spring-cloud-gateway/README.md)
⬅️上一个教程:[08 - 构建Spring Cloud网关](../08-build-a-spring-cloud-gateway/README.md)
➡️ Next guide: [10 - Blue/Green deployment](../10-blue-green-deployment/README.md)
➡️下一个教程:[10 - 蓝/绿部署](../10-blue-green-deployment/README.md)

Просмотреть файл

@ -0,0 +1,72 @@
# 09 - Putting it all together, a complete microservice stack
__This guide is part of the [Azure Spring Cloud training](../README.md)__
Now that we have made two microservices publicly available, we will incorporate a user interface to see them in action. Then, we will use Azure Monitor to monitor the flow of traffic to and among our services and to track metrics.
---
## Add a front-end to the microservices stack
We now have a complete microservices stack:
- A gateway based on Spring Cloud Gateway.
- A reactive `city-service` microservice, that stores its data on Cosmos DB.
- A `weather-service` microservice, that stores its data on MySQL
In order to finish this architecture, we need to add a front-end to it:
- We've already built a VueJS application, that is available in the ["weather-app" folder](weather-app/).
- This front-end could be hosted in Azure Spring Cloud, using the same domain name (this won't be the case in this guide, and that's why we enabled CORS in our gateway earlier).
- If you are familiar with NodeJS and Vue CLI, you can run this application locally by typing `npm install && vue ui`.
In order to simplify this part, which is not relevant to understanding Spring Cloud, we have already built a running front-end:
__[https://spring-training.azureedge.net/](https://spring-training.azureedge.net/)__
For your information, this website is hosted on Azure Storage and served through Azure CDN for optimum performance.
Go to [https://spring-training.azureedge.net/](https://spring-training.azureedge.net/), input your Spring Cloud Gateway's public URL in the text field and click on "Go". You should see the following screen:
![VueJS front-end](media/01-vuejs-frontend.png)
## Review the distributed tracing to better understand the architecture
We have already enabled distributed tracing on our Azure Spring Cloud instance in Section 1 by adding the `--enable-java-agent` flag to the create command.
Now, you can use the VueJS application on [https://spring-training.azureedge.net/](https://spring-training.azureedge.net/) to generate some traffic on the microservices stack.
>💡 Tracing data can take a couple of minutes to be ingested by the system, so use this time to generate some load.
In the "Application Insights" menu in Azure Portal, you should now have access to a full application map, as well as a search engine that allows you to find performance bottlenecks.
![Distributed tracing](media/02-distributed-tracing.png)
> 💡 If your application map looks different from the one above, select the hierarchical view from the layout switch in the top-right corner:
>
> ![layout switch](media/05-layout-switch.png)
## Review the performance metrics
Open a more holistic view at the `Performance` blade where you can see response times and request counts for operations exposed by your applications.
![Trace detail](media/03-trace-detail.png)
For even more detailed data, navigate to the `Dependencies` tab in the `Performance` blade where you can see all your dependencies and their response times and request counts.
## Scale applications
Now that distributed tracing is enabled, we can scale applications depending on our needs.
- Go to [the Azure portal](https://portal.azure.com/?WT.mc_id=azurespringcloud-github-judubois).
- Go to the overview page of your Azure Spring Cloud server and select "Apps" in the menu.
- Select one service and click on "Scale Out" in the menu. Select the service that you want to scale out.
![Application scaling](media/04-scale-out.png)
- Modify the number of instances to manually scale the service. You can also set custom auto scaling based on metrics.
![Application scaling](media/04b-auto-scaling.png)
---
⬅️ Previous guide: [08 - Build a Spring Cloud Gateway](../08-build-a-spring-cloud-gateway/README.md)
➡️ Next guide: [10 - Blue/Green deployment](../10-blue-green-deployment/README.md)

Просмотреть файл

@ -1,20 +1,21 @@
# 10 - Blue/Green deployment
# 10 - 蓝/绿部署
__This guide is part of the [Azure Spring Cloud training](../README.md)__
**本教程是[Azure Spring Cloud 培训](../README.md)系列之一**
The blue-green deployment pattern allows you to test latest application changes on production infrastructure, but without exposing the changes to consumers until your testing is complete. In this section, we'll perform a blue-green deployment with Azure CLI. Although we will go through the deployment steps manually, the Azure CLI commands we'll use can be automated in a CI/CD pipeline.
蓝绿部署模式允许您在生产基础设施上测试最新的应用程序更改,但在测试完成之前不会向最终用户暴露这些更改。在本节中,我们将与 Azure CLI 一起执行蓝绿部署。虽然我们将手动完成部署步骤,但我们也可以使用 Azure CLI 命令在 CI/CD Pipeline中实现自动化。
---
We are going to deploy a new release of the "weather-service" microservice that was developed in [07 - Build a Spring Boot microservice using MySQL](../07-build-a-spring-boot-microservice-using-mysql/README.md).
我们将部署新版本的"weather-service"微服务,这是基于之前的实验[07 - 使用 MySQL 构建Spring Boot微服务](../07-build-a-spring-boot-microservice-using-mysql/README.md).
The microservice that we develop in this guide is [available here](weather-service/), which is a slightly modified version of the service that was developed earlier.
我们在本教程中开发的微服务[可参考这里](weather-service/),这是基于之前开发的一个稍作修改的服务版本。
## Modify the current application
## 修改当前应用程序
In the "weather-service" application, commit your current code and switch to a new branch where you will do your changes.
在"weather-service"应用程序中,提交当前代码并切换到新的分支,来进行修改。
Open the `WeatherController` class and modify its `getWeatherForCity()` method so it always returns sunny weather (this will be an easy-to-spot graphical view of our modifications in the code):
打开`WeatherController`类和修改其`getWeatherForCity()`方法,让它总是返回阳光明媚的天气(这样我们在前端更容易的看到版本变更是否生效):
```java
package com.example.demo;
@ -43,9 +44,9 @@ public class WeatherController {
}
```
## Deploy the new application to a new "green" deployment
## 将新应用程序部署到新的"绿色"部署
Build a new version of the application and deploy it to a new `deployment` called `green`:
构建应用程序的新版本并将其部署到新版本`deployment`叫`green`:
```bash
cd weather-service
@ -54,50 +55,50 @@ az spring-cloud app deployment create --name green --app weather-service --jar-p
cd ..
```
Once the application is deployed, if you go to [https://spring-training.azureedge.net/](https://spring-training.azureedge.net/) you will still have the same data, as the new version of the microservice is now in a staging area and not in production yet.
一旦应用程序部署成功,如果你去<https://spring-training.azureedge.net/>您仍将看到的是修改之前的版本,因为新版本的微服务现在处于暂存(Stage)区域,尚未在生产中。
Navigate to the Azure Spring Cloud instance in [the Azure portal](https://portal.azure.com/?WT.mc_id=azurespringcloud-github-judubois) and click on "Deployments" (under Settings). You should now see the "green" deployment in the "Staging Deployment" column:
导航到Azure Spring Cloud实例[Azure门户网站](https://portal.azure.com/?WT.mc_id=azurespringcloud-github-judubois)然后单击"部署"(在"设置"下)。现在,您应该在"阶段部署"列中看到"绿色"部署:
![Deployment Pane](media/02-deployment-pane.png)
You can test the `green` deployment by invoking the same URL as in section 7, but replacing the deployment name `default` with `green`:
您可以测试`green`, 通过调用与第7节相同的URL但需要替换部署名称`default`为`green`:
```bash
curl https://***.test.azuremicroservices.io/weather-service/green/weather/city?name=Paris%2C%20France
```
And you should see the result of the recent modification:
您应该看到最近修改的结果:
```json
{"city":"Paris, France","description":"It's always sunny on Azure Spring Cloud","icon":"weather-sunny"}
```
Note: we're not testing the green deployment through the `gateway` application. The purpose of a green deployment is to test changes to a microservice before routing production traffic to it. Therefore, if you access `weather-service` through the public Gateway URL, as you did in section 8, you will be routed to the original version of the service.
注意:我们不会通过`gateway`来调用。绿色部署的目的是在将正式生产流量路由到微型服务之前,对微服务的更改进行测试。因此,如果您通过公共网关网址访问`weather-service`,正如您在第 8 节所做的那样,您将被路由到服务的原始版本。
To put this `green` deployment into production, you can use the command line:
把这个`green`部署到生产中,您可以使用命令行:
```bash
az spring-cloud app set-deployment -n weather-service --deployment green
```
Another solution is to use [the Azure portal](https://portal.azure.com/?WT.mc_id=azurespringcloud-github-judubois):
另一种解决方案是使用[Azure门户网站](https://portal.azure.com/):
- Find your Azure Spring Cloud instance
- Click on the "deployment" menu
- Select the `weather-service` application and click on "Set deployment"
- 查找您的Azure Spring Cloud实例
- 单击"部署"菜单
- 选择`weather-service`应用程序并单击"设置部署"
> If you want to reuse a deployment name, you need first to delete the previous deployment under that name:
> 如果您想重复使用部署名称,请首先删除该名称下以前的部署:
>
> ```bash
> az spring-cloud app deployment delete --name green --app weather-service
> ```
Once you have swapped deployments and see that `green` is active, you need to wait a few seconds for the Spring Cloud Service Registry to synchronize and use this new version from the `gateway` application. You will then be able to see the new modified data:
一旦您交换了部署,就会看到`green`是激活的,您需要等待几秒钟, 让`gateway`应用从 Spring Cloud Service Registry 同步和使用这个新版本。之后,您将能够看到新的修改数据:
![Green deployment](media/01-green-deployment.png)
---
⬅️ Previous guide: [09 - Putting it all together, a complete microservice stack](../09-putting-it-all-together-a-complete-microservice-stack/README.md)
⬅️上一个教程:[09 - 综上所述,一个完整的微服务堆栈](../09-putting-it-all-together-a-complete-microservice-stack/README.md)
➡️ Next guide: [11 - Configure CI/CD](../11-configure-ci-cd/README.md)
➡️下一个教程:[11 - 配置 CI/CD](../11-configure-ci-cd/README.md)

Просмотреть файл

@ -0,0 +1,103 @@
# 10 - Blue/Green deployment
__This guide is part of the [Azure Spring Cloud training](../README.md)__
The blue-green deployment pattern allows you to test latest application changes on production infrastructure, but without exposing the changes to consumers until your testing is complete. In this section, we'll perform a blue-green deployment with Azure CLI. Although we will go through the deployment steps manually, the Azure CLI commands we'll use can be automated in a CI/CD pipeline.
---
We are going to deploy a new release of the "weather-service" microservice that was developed in [07 - Build a Spring Boot microservice using MySQL](../07-build-a-spring-boot-microservice-using-mysql/README.md).
The microservice that we develop in this guide is [available here](weather-service/), which is a slightly modified version of the service that was developed earlier.
## Modify the current application
In the "weather-service" application, commit your current code and switch to a new branch where you will do your changes.
Open the `WeatherController` class and modify its `getWeatherForCity()` method so it always returns sunny weather (this will be an easy-to-spot graphical view of our modifications in the code):
```java
package com.example.demo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
@Controller
@RequestMapping(path="/weather")
public class WeatherController {
private final WeatherRepository weatherRepository;
public WeatherController(WeatherRepository weatherRepository) {
this.weatherRepository = weatherRepository;
}
@GetMapping("/city")
public @ResponseBody Weather getWeatherForCity(@RequestParam("name") String cityName) {
return weatherRepository.findById(cityName).map(weather -> {
weather.setDescription("It's always sunny on Azure Spring Cloud");
weather.setIcon("weather-sunny");
return weather;
}).get();
}
}
```
## Deploy the new application to a new "green" deployment
Build a new version of the application and deploy it to a new `deployment` called `green`:
```bash
cd weather-service
./mvnw clean package -DskipTests
az spring-cloud app deployment create --name green --app weather-service --jar-path target/demo-0.0.1-SNAPSHOT.jar
cd ..
```
Once the application is deployed, if you go to [https://spring-training.azureedge.net/](https://spring-training.azureedge.net/) you will still have the same data, as the new version of the microservice is now in a staging area and not in production yet.
Navigate to the Azure Spring Cloud instance in [the Azure portal](https://portal.azure.com/?WT.mc_id=azurespringcloud-github-judubois) and click on "Deployments" (under Settings). You should now see the "green" deployment in the "Staging Deployment" column:
![Deployment Pane](media/02-deployment-pane.png)
You can test the `green` deployment by invoking the same URL as in section 7, but replacing the deployment name `default` with `green`:
```bash
curl https://***.test.azuremicroservices.io/weather-service/green/weather/city?name=Paris%2C%20France
```
And you should see the result of the recent modification:
```json
{"city":"Paris, France","description":"It's always sunny on Azure Spring Cloud","icon":"weather-sunny"}
```
Note: we're not testing the green deployment through the `gateway` application. The purpose of a green deployment is to test changes to a microservice before routing production traffic to it. Therefore, if you access `weather-service` through the public Gateway URL, as you did in section 8, you will be routed to the original version of the service.
To put this `green` deployment into production, you can use the command line:
```bash
az spring-cloud app set-deployment -n weather-service --deployment green
```
Another solution is to use [the Azure portal](https://portal.azure.com/?WT.mc_id=azurespringcloud-github-judubois):
- Find your Azure Spring Cloud instance
- Click on the "deployment" menu
- Select the `weather-service` application and click on "Set deployment"
> If you want to reuse a deployment name, you need first to delete the previous deployment under that name:
>
> ```bash
> az spring-cloud app deployment delete --name green --app weather-service
> ```
Once you have swapped deployments and see that `green` is active, you need to wait a few seconds for the Spring Cloud Service Registry to synchronize and use this new version from the `gateway` application. You will then be able to see the new modified data:
![Green deployment](media/01-green-deployment.png)
---
⬅️ Previous guide: [09 - Putting it all together, a complete microservice stack](../09-putting-it-all-together-a-complete-microservice-stack/README.md)
➡️ Next guide: [11 - Configure CI/CD](../11-configure-ci-cd/README.md)

Просмотреть файл

@ -1,20 +1,21 @@
# 11 - Configure CI/CD
# 11 - 配置 CI/CD
__This guide is part of the [Azure Spring Cloud training](../README.md)__
**本教程是[Azure Spring Cloud 培训](../README.md)系列之一**
In this section, we will use GitHub Actions to implement continuous deployment to Azure Spring Cloud. For simplicity, we will not implement blue-green deployments in this section, but don't hesitate to come back and add blue-green deployments after completing the remainder of the tutorial.
在本节中,我们将使用 GitHub Action对 Azure Spring Cloud实施持续部署。为了简化我们不会在本节中实施蓝绿部署但在完成教程后您也就知道如何实现自动蓝绿部署了。
---
Our microservices and gateway are easy to deploy manually, but it is of course better to automate all those tasks! We are going to use [GitHub actions](https://github.com/features/actions) as a Continuous Integration / Continuous Deployment platform (or CI/CD for short). This configuration is rather simple, so it should be trivial to port it to another CI/CD platform.
我们的微服务和网关很容易手动部署,但当然最好实现所有这些任务的自动化!我们将使用[Github Action](https://github.com/features/actions)作为一个持续集成/持续部署平台简称CI/CD。这种配置相当简单因此将其移植到另一个 CI/CD 平台也应该很轻易了。
We are going to automate the deployment of the `weather-service` microservice that was developed in [07 - Build a Spring Boot microservice using MySQL](../07-build-a-spring-boot-microservice-using-mysql/README.md). It is exactly the same configuration that would need to be done for the `city-service` microservice and the gateway, so if you want to automate them too, you can just copy/paste what is being done in the current guide.
我们将自动化部署`weather-service`,这是在之前实现的 - [07 - 使用 MySQL 构建Spring Boot微服务](../07-build-a-spring-boot-microservice-using-mysql/README.md). 其他的 `city-service`微服务和Gateway网关也是完全一样的配置步骤所以你只需重复复制/粘贴这教程的脚本即可。
## Configure GitHub
## 配置Github
[Create a new GitHub repository](https://github.com/new) and commit the code from the `weather-service` microservice into that repository:
[创建新的 GitHub 存储库](https://github.com/new)并从`weather-service`微服务提交代码到该存储库:
> 🛑 Make sure you substitute the Git URL from your own github repository (make sure you use the HTTPS URL, not the SSH URL). This should be a different repository than the one you used to store configuration in section 4. If a login dialog appears, log in with your regular GitHub credentials.
> 🛑确保您替换 Git URL 为自己的 github 存储库(确保您使用 HTTPS URL而不是 SSH URL。这应该是一个跟您在第 4 节配置的存储库不同的。如果弹出登录对话,请使用常规 GitHub 凭据来登录。
```bash
cd weather-service
@ -26,9 +27,9 @@ git push origin master
cd ..
```
You now need to allow access from your GitHub workflow to your Azure Spring Cloud instance. Open up a terminal and type the following command, replacing `$AZ_RESOURCE_GROUP` with the name of your resource group.
您现在需要允许从 GitHub Workflow访问您的 Azure Spring Cloud实例。打开终端并键入以下命令替换`$AZ_RESOURCE_GROUP`与您的资源组的名称。
🛑 Make sure you assign the name of your resource group to the variable `AZ_RESOURCE_GROUP` or substitute the value for it in the commands below.
🛑确保将资源组的名称分配给变量`AZ_RESOURCE_GROUP`或在下面的命令中替换其值。
```bash
# Prevents a Git bash issue. Not necessary outside of Windows:
@ -39,20 +40,20 @@ RESOURCE_ID=$(az group show --name "$AZ_RESOURCE_GROUP" --query id -o tsv)
# Create a service principal with a Contributor role to the resource group.
SPNAME="sp-$(az spring-cloud list --query '[].name' -o tsv)"
az ad sp create-for-rbac --name "${SPNAME}" --role contributor --scopes "$RESOURCE_ID" --sdk-auth
az ad sp create-for-rbac --name "${SPNAME}" --role contributor --scopes "$RESOURCE_ID" --sdk-auth -o json
```
This should output a JSON text, that you need to copy.
这应该输出一个JSON文本你需要复制保留下来。
Then, in your GitHub project, select `Settings > Secrets` and add a new secret called `AZURE_CREDENTIALS`. Paste the JSON text you just copied into that secret.
然后,在 GitHub 项目中,选择`Settings > Secrets`并添加一个新的秘密称为`AZURE_CREDENTIALS`.粘贴你刚刚复制到那个Secrect的JSON文本。
## Create a GitHub Action
## 创建一个Github Action
Inside the `weather-service` directory, create a new directory called `.github/workflows` and add a file called `azure-spring-cloud.yml` in it. This file is a GitHub workflow and will use the secret we just configured above to deploy the application to your Azure Spring Cloud instance.
在`weather-service`目录,创建一个新的目录称为`.github/workflows`并在里面添加一个yml文件`azure-spring-cloud.yml`。此文件是 GitHub Workflow将使用我们上面刚刚配置的Secrect将应用程序部署到您的 Azure Spring Cloud实例。
In that file, copy/paste the following content, performing the indicated substitutions:
在该文件中,复制/粘贴以下内容,并按提示替换内容:
>🛑 You must substitute the name of your Azure Spring Cloud instance for `<AZ_SPRING_CLOUD_NAME>` and the name of the resource group for `<AZ_RESOURCE_GROUP>` in the YAML below.
> 🛑在下面的yaml, 您必须将Azure Spring Cloud实例的名称和资源组的名称替换为`<AZ_SPRING_CLOUD_NAME>``<AZ_RESOURCE_GROUP>`。
```yaml
name: Build and deploy to Azure Spring Cloud
@ -80,29 +81,29 @@ jobs:
run: az spring-cloud app deploy --resource-group <AZ_RESOURCE_GROUP> --service <AZ_SPRING_CLOUD_NAME> --name weather-service --jar-path target/demo-0.0.1-SNAPSHOT.jar
```
This workflow does the following:
此Workflow有以下几点
- It sets up the JDK
- It compiles and packages the application using Maven
- It authenticates to Azure Spring Cloud using the credentials we just configured
- It adds the Azure Spring Cloud extensions to the Azure CLI (this step should disappear when the service is in final release)
- It deploys the application to your Azure Spring Cloud instance
- 设置了JDK
- 使用 Maven 编译和打包应用程序
- 使用我们刚刚配置的凭据验证到Azure Spring Cloud
- 将 Azure Spring Cloud扩展添加到 Azure CLI此步骤应在服务最终发布时可略去
- 它将应用程序部署到您的 Azure Spring Cloud实例
This workflow is configured to be triggered whenever code is pushed to the repository.
There are many other [events that trigger GitHub actions](https://help.github.com/en/articles/events-that-trigger-workflows). You could, for example, deploy each time a new tag is created on the project.
当代码被Push到存储库时此Workflow被配置为触发。
还有很多其他[触发 GitHub Action的事件](https://help.github.com/en/articles/events-that-trigger-workflows).例如,每次在项目上创建新标签时,也可以触发自动部署。
## Test the GitHub Action
## 测试Github Action
You can now commit and push the `azure-spring-cloud.yml` file we just created.
您现在可以Commit 并 Push 我们刚刚创建的文件 `azure-spring-cloud.yml`
Going to the `Actions` tab of your GitHub project, you should see that your project is automatically built and deployed to your Azure Spring Cloud instance:
去您的 GitHub 项目`Actions`选项卡,您应该会看到您的项目是自动构建并部署到您的 Azure Spring Cloud实例
![GitHub workflow](media/01-github-workflow.png)
Congratulations! Each time you `git push` your code, your microservice is now automatically deployed to production.
恭喜!现在每次你`git push`您的代码后,您的微服务将自动部署到生产环境了。
---
⬅️ Previous guide: [10 - Blue/Green deployment](../10-blue-green-deployment/README.md)
⬅️上一个教程:[10 - 蓝/绿部署](../10-blue-green-deployment/README.md)
➡️ Next guide: [12 - Making Microservices Talk To Each Other](../12-making-microservices-talk-to-each-other/README.md)
➡️下一个教程:[12 - 微服务间的相互调用](../12-making-microservices-talk-to-each-other/README.md)

Просмотреть файл

@ -0,0 +1,108 @@
# 11 - Configure CI/CD
__This guide is part of the [Azure Spring Cloud training](../README.md)__
In this section, we will use GitHub Actions to implement continuous deployment to Azure Spring Cloud. For simplicity, we will not implement blue-green deployments in this section, but don't hesitate to come back and add blue-green deployments after completing the remainder of the tutorial.
---
Our microservices and gateway are easy to deploy manually, but it is of course better to automate all those tasks! We are going to use [GitHub actions](https://github.com/features/actions) as a Continuous Integration / Continuous Deployment platform (or CI/CD for short). This configuration is rather simple, so it should be trivial to port it to another CI/CD platform.
We are going to automate the deployment of the `weather-service` microservice that was developed in [07 - Build a Spring Boot microservice using MySQL](../07-build-a-spring-boot-microservice-using-mysql/README.md). It is exactly the same configuration that would need to be done for the `city-service` microservice and the gateway, so if you want to automate them too, you can just copy/paste what is being done in the current guide.
## Configure GitHub
[Create a new GitHub repository](https://github.com/new) and commit the code from the `weather-service` microservice into that repository:
> 🛑 Make sure you substitute the Git URL from your own github repository (make sure you use the HTTPS URL, not the SSH URL). This should be a different repository than the one you used to store configuration in section 4. If a login dialog appears, log in with your regular GitHub credentials.
```bash
cd weather-service
git init
git add .
git commit -m 'Initial commit'
git remote add origin <GIT HTTPS URL HERE>
git push origin master
cd ..
```
You now need to allow access from your GitHub workflow to your Azure Spring Cloud instance. Open up a terminal and type the following command, replacing `$AZ_RESOURCE_GROUP` with the name of your resource group.
🛑 Make sure you assign the name of your resource group to the variable `AZ_RESOURCE_GROUP` or substitute the value for it in the commands below.
```bash
# Prevents a Git bash issue. Not necessary outside of Windows:
export MSYS_NO_PATHCONV=1
# Get the ARM resource ID of the resource group
RESOURCE_ID=$(az group show --name "$AZ_RESOURCE_GROUP" --query id -o tsv)
# Create a service principal with a Contributor role to the resource group.
SPNAME="sp-$(az spring-cloud list --query '[].name' -o tsv)"
az ad sp create-for-rbac --name "${SPNAME}" --role contributor --scopes "$RESOURCE_ID" --sdk-auth
```
This should output a JSON text, that you need to copy.
Then, in your GitHub project, select `Settings > Secrets` and add a new secret called `AZURE_CREDENTIALS`. Paste the JSON text you just copied into that secret.
## Create a GitHub Action
Inside the `weather-service` directory, create a new directory called `.github/workflows` and add a file called `azure-spring-cloud.yml` in it. This file is a GitHub workflow and will use the secret we just configured above to deploy the application to your Azure Spring Cloud instance.
In that file, copy/paste the following content, performing the indicated substitutions:
>🛑 You must substitute the name of your Azure Spring Cloud instance for `<AZ_SPRING_CLOUD_NAME>` and the name of the resource group for `<AZ_RESOURCE_GROUP>` in the YAML below.
```yaml
name: Build and deploy to Azure Spring Cloud
on: [push]
jobs:
build-and-deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up JDK 1.8
uses: actions/setup-java@v1
with:
java-version: 1.8
- name: Build with Maven
run: mvn package -DskipTests
- name: Login to Azure Spring Cloud
uses: azure/login@v1
with:
creds: ${{ secrets.AZURE_CREDENTIALS }}
- name: Install Azure Spring Cloud extension
run: az extension add -y --name spring-cloud
- name: Deploy to Azure Spring Cloud
run: az spring-cloud app deploy --resource-group <AZ_RESOURCE_GROUP> --service <AZ_SPRING_CLOUD_NAME> --name weather-service --jar-path target/demo-0.0.1-SNAPSHOT.jar
```
This workflow does the following:
- It sets up the JDK
- It compiles and packages the application using Maven
- It authenticates to Azure Spring Cloud using the credentials we just configured
- It adds the Azure Spring Cloud extensions to the Azure CLI (this step should disappear when the service is in final release)
- It deploys the application to your Azure Spring Cloud instance
This workflow is configured to be triggered whenever code is pushed to the repository.
There are many other [events that trigger GitHub actions](https://help.github.com/en/articles/events-that-trigger-workflows). You could, for example, deploy each time a new tag is created on the project.
## Test the GitHub Action
You can now commit and push the `azure-spring-cloud.yml` file we just created.
Going to the `Actions` tab of your GitHub project, you should see that your project is automatically built and deployed to your Azure Spring Cloud instance:
![GitHub workflow](media/01-github-workflow.png)
Congratulations! Each time you `git push` your code, your microservice is now automatically deployed to production.
---
⬅️ Previous guide: [10 - Blue/Green deployment](../10-blue-green-deployment/README.md)
➡️ Next guide: [12 - Making Microservices Talk To Each Other](../12-making-microservices-talk-to-each-other/README.md)

Просмотреть файл

@ -1,30 +1,31 @@
# 12 - Making Microservices Talk to Each Other
# 12 - 微服务间的相互调用
__This guide is part of the [Azure Spring Cloud training](../README.md)__
**本教程是[Azure Spring Cloud 培训](../README.md)系列之一**
Creating a microservice that talks to other microservices.
创建与其他微服务通讯的微服务。
---
In [Section 6](../06-build-a-reactive-spring-boot-microservice-using-cosmos/README.md) we deployed a microservice that returns a list of cities. In [Section 7](../07-build-a-spring-boot-microservice-using-mysql/README.md), we deployed a microservice that, given a city, returns the weather for that city. And in [Section 9](../09-putting-it-all-together-a-complete-microservice-stack/README.md), we created a front-end application that queries these two microservices.
在[第6节](../06-build-a-reactive-spring-boot-microservice-using-cosmos/README.md)我们部署了一个微服务,返回一个城市列表。在[第7节](../07-build-a-spring-boot-microservice-using-mysql/README.md),我们部署了一个微型服务,给一个城市,返回该城市的天气。并在[第9节](../09-putting-it-all-together-a-complete-microservice-stack/README.md),我们创建了一个前端应用程序,来调用这两个微服务。
There is a glaring inefficiency in this design: the browser first calls `city-service`, waits for it to respond, and upon getting that response, calls `weather-service` for each of the cities returned. All these remote calls are made over public internet, whose speed is never guaranteed.
这种设计效率明显低下:浏览器首先调用`city-service`,等待它响应,并在得到该响应后,再基于每个城市调用`weather-service`获得返回。所有这些远程调用都是通过公共互联网进行的,其访问速度很难得到保证。
To resolve this inefficiency, we will create a single microservice that implements the [Transaction Script](https://www.martinfowler.com/eaaCatalog/transactionScript.html) pattern: it will orchestrate the calls to individual microservices and return the weather for all cities. To do this, we will use [Spring Cloud OpenFeign]. OpenFeign will automatically obtain the URLs of invoked microservices from Spring Cloud Registry, allowing us to build our `all-cities-weather-services` microservice without needing to resolve the locations of the constituent microservices.
为了改进这种低效率,我们将创建一个入口的微服务,实现[交易脚本](https://www.martinfowler.com/eaaCatalog/transactionScript.html)模式:它将协调各个微服务的调用,并返回所有城市的天气。为此,我们将使用[Spring Cloud OpenFeign]. OpenFeign 将从Spring Cloud Registry自动获取调用的微服务的地址从而方便我们构建微服务`all-cities-weather-services`,无需关心其他微服务的位置。
Note how the code we create in this section is endpoint-agnostic. All we specify is the name of the services we want to invoke in the `@FeignClient` annotation. OpenFeign and Spring Cloud Registry then work together behind the scenes to connect our new microservice to the services we've created previously.
请注意我们在本节中创建的代码是适用于任意endpoint的。我们需要指定的就是在`@FeignClient`的注解。然后OpenFeign 和Spring Cloud Registry 在幕后合作,将我们的新微服务连接到之前创建的服务。
## Create a Spring Boot Microservice
## 创建Spring Boot微服务
To create our microservice, we will invoke the Spring Initalizer service from the command line:
我们从命令行调用Spring Initalizer服务为来创建新的微服务
```bash
curl https://start.spring.io/starter.tgz -d dependencies=cloud-feign,web,cloud-eureka,cloud-config-client -d baseDir=all-cities-weather-service -d bootVersion=2.3.8 -d javaVersion=1.8 | tar -xzvf -
```
## Add Spring code to call other microservices
## 添加Spring代码调用其他微服务
Next to the `DemoApplication` class, create a `Weather` class:
在`DemoApplication`类同一目录下,创建一个`Weather`类:
```java
package com.example.demo;
@ -63,9 +64,9 @@ public class Weather {
}
```
Note: this is the same `Weather` class that we created in Section 7 when we defined the original `weather-service` with one important difference: we no longer annotate the class as a JPA entity for data retrieval.
注意这是跟我们在第7节创建的类`Weather`是基本一样的,与我们原来在`weather-service`定义的有一个唯一的区别是我们不再将该类注释为用于数据检索的JPA实体。
Next, in the same location create the `City` class. This is the same `City` class that we created in Section 6.
接下来,在同一位置创建`City`类。这与我们在第6节创建的类`City`是基本一样的。
```java
package com.example.demo;
@ -84,7 +85,7 @@ public class City {
}
```
Then, in the same location, create an interface called `CityServiceClient` with the following contents. When we run our new service, OpenFeign will automatically provide an implementation for this interface.
然后,在同一位置创建一个名为`CityServiceClient`的接口类内容如下。当我们运行新服务时OpenFeign 将自动为此接口提供实现。
```java
package com.example.demo;
@ -103,7 +104,7 @@ public interface CityServiceClient{
```
Create a similar OpenFeign client interface for the weather service, named `WeatherServiceClient`.
为weather-service创建一个类似的 OpenFeign 客户端接口,命名为`WeatherServiceClient`.
```java
package com.example.demo;
@ -126,7 +127,7 @@ public interface WeatherServiceClient{
```
To enable Spring Cloud to discovery the underlying services and to automatically generate OpenFeign clients, add the annotations @EnableDiscoveryClient and @EnableFeignClients to the `DemoApplication` class (as well as the corresponding `import` statements):
要使 Spring Cloud 能够发现基础服务并自动生成 OpenFeign 客户端,需要在`DemoApplication`类添加注释 @EnableDiscoveryClient@EnableFeignClients,(以及相应的`import`声明):
```java
package com.example.demo;
@ -146,7 +147,7 @@ public class DemoApplication {
}
```
Everything is now in place to implement the `all-cities-weather-service`. Create the class `AllCitiesWeatherController` as follows:
现在一切都就位了,可以开始实现`all-cities-weather-service`. 创建类`AllCitiesWeatherController`如下:
```java
package com.example.demo;
@ -186,26 +187,27 @@ public class AllCitiesWeatherController {
}
}
```
## Add time-out settings
In order to stop the Feign services timing out automatically, open up the `src/main/resources/application.properties` file and add:
## 添加超时设置
为了阻止 Feign 服务自动超时,请打开`src/main/resources/application.properties`文件并添加:
```properties
feign.client.config.default.connectTimeout=160000000
feign.client.config.default.readTimeout=160000000
```
## Create the application on Azure Spring Cloud
## 在Azure Spring Cloud上创建应用程序
As before, create a specific `all-cities-weather-service` application in your Azure Spring Cloud instance:
和以前一样,创建一个特定的`all-cities-weather-service`应用在您的Azure Spring Cloud实例中
```bash
az spring-cloud app create -n all-cities-weather-service
```
## Deploy the application
## 部署应用程序
You can now build your "all-cities-weather-service" project and send it to Azure Spring Cloud:
现在,您可以编译您的"all-cities-weather-service"项目,并将其发送到 Azure Spring Cloud中
```bash
cd all-cities-weather-service
@ -214,17 +216,17 @@ az spring-cloud app deploy -n all-cities-weather-service --jar-path target/demo-
cd ..
```
## Test the project in the cloud
## 在云中测试项目
You can use the gateway created in Section 8 to access the all-cities-weather-service directly.
您可以使用第 8 节中创建的网关直接访问全城市天气服务。
>💡__Note:__ the trailing slash (`/`) is not optional.
> 💡**注意:**尾随斜线(`/`)是必须的。
```bash
https://<Your gateway URL>/ALL-CITIES-WEATHER-SERVICE/
```
You should get the JSON output with the weather for all the cities:
您应该获得 JSON 输出与所有城市的天气:
```json
[{"city":"Paris, France","description":"It's always sunny on Azure Spring Cloud","icon":"weather-sunny"},
@ -233,6 +235,6 @@ You should get the JSON output with the weather for all the cities:
---
⬅️ Previous guide: [11 - Configure CI/CD](../11-configure-ci-cd/README.md)
⬅️上一个教程:[11 - 配置 CI/CD](../11-configure-ci-cd/README.md)
➡️ Next guide: [Conclusion](../99-conclusion/README.md)
➡️下一个教程:[总结](../99-conclusion/README.md)

Просмотреть файл

@ -0,0 +1,238 @@
# 12 - Making Microservices Talk to Each Other
__This guide is part of the [Azure Spring Cloud training](../README.md)__
Creating a microservice that talks to other microservices.
---
In [Section 6](../06-build-a-reactive-spring-boot-microservice-using-cosmos/README.md) we deployed a microservice that returns a list of cities. In [Section 7](../07-build-a-spring-boot-microservice-using-mysql/README.md), we deployed a microservice that, given a city, returns the weather for that city. And in [Section 9](../09-putting-it-all-together-a-complete-microservice-stack/README.md), we created a front-end application that queries these two microservices.
There is a glaring inefficiency in this design: the browser first calls `city-service`, waits for it to respond, and upon getting that response, calls `weather-service` for each of the cities returned. All these remote calls are made over public internet, whose speed is never guaranteed.
To resolve this inefficiency, we will create a single microservice that implements the [Transaction Script](https://www.martinfowler.com/eaaCatalog/transactionScript.html) pattern: it will orchestrate the calls to individual microservices and return the weather for all cities. To do this, we will use [Spring Cloud OpenFeign]. OpenFeign will automatically obtain the URLs of invoked microservices from Spring Cloud Registry, allowing us to build our `all-cities-weather-services` microservice without needing to resolve the locations of the constituent microservices.
Note how the code we create in this section is endpoint-agnostic. All we specify is the name of the services we want to invoke in the `@FeignClient` annotation. OpenFeign and Spring Cloud Registry then work together behind the scenes to connect our new microservice to the services we've created previously.
## Create a Spring Boot Microservice
To create our microservice, we will invoke the Spring Initalizer service from the command line:
```bash
curl https://start.spring.io/starter.tgz -d dependencies=cloud-feign,web,cloud-eureka,cloud-config-client -d baseDir=all-cities-weather-service -d bootVersion=2.3.8 -d javaVersion=1.8 | tar -xzvf -
```
## Add Spring code to call other microservices
Next to the `DemoApplication` class, create a `Weather` class:
```java
package com.example.demo;
public class Weather {
private String city;
private String description;
private String icon;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
}
```
Note: this is the same `Weather` class that we created in Section 7 when we defined the original `weather-service` with one important difference: we no longer annotate the class as a JPA entity for data retrieval.
Next, in the same location create the `City` class. This is the same `City` class that we created in Section 6.
```java
package com.example.demo;
public class City {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
```
Then, in the same location, create an interface called `CityServiceClient` with the following contents. When we run our new service, OpenFeign will automatically provide an implementation for this interface.
```java
package com.example.demo;
import java.util.List;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
@FeignClient("city-service")
public interface CityServiceClient{
@GetMapping("/cities")
List<List<City>> getAllCities();
}
```
Create a similar OpenFeign client interface for the weather service, named `WeatherServiceClient`.
```java
package com.example.demo;
import com.example.demo.Weather;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@FeignClient("weather-service")
@RequestMapping("/weather")
public interface WeatherServiceClient{
@GetMapping("/city")
Weather getWeatherForCity(@RequestParam("name") String cityName);
}
```
To enable Spring Cloud to discovery the underlying services and to automatically generate OpenFeign clients, add the annotations @EnableDiscoveryClient and @EnableFeignClients to the `DemoApplication` class (as well as the corresponding `import` statements):
```java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
```
Everything is now in place to implement the `all-cities-weather-service`. Create the class `AllCitiesWeatherController` as follows:
```java
package com.example.demo;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.example.demo.City;
import com.example.demo.CityServiceClient;
import com.example.demo.Weather;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class AllCitiesWeatherController {
@Autowired
private CityServiceClient cityServiceClient;
@Autowired
private WeatherServiceClient weatherServiceClient;
@GetMapping("/")
public List<Weather> getAllCitiesWeather(){
Stream<City> allCities = cityServiceClient.getAllCities().stream().flatMap(list -> list.stream());
//Obtain weather for all cities in parallel
List<Weather> allCitiesWeather = allCities.parallel()
.peek(city -> System.out.println("City: >>"+city.getName()+"<<"))
.map(city -> weatherServiceClient.getWeatherForCity(city.getName()))
.collect(Collectors.toList());
return allCitiesWeather;
}
}
```
## Add time-out settings
In order to stop the Feign services timing out automatically, open up the `src/main/resources/application.properties` file and add:
```properties
feign.client.config.default.connectTimeout=160000000
feign.client.config.default.readTimeout=160000000
```
## Create the application on Azure Spring Cloud
As before, create a specific `all-cities-weather-service` application in your Azure Spring Cloud instance:
```bash
az spring-cloud app create -n all-cities-weather-service
```
## Deploy the application
You can now build your "all-cities-weather-service" project and send it to Azure Spring Cloud:
```bash
cd all-cities-weather-service
./mvnw clean package -DskipTests
az spring-cloud app deploy -n all-cities-weather-service --jar-path target/demo-0.0.1-SNAPSHOT.jar
cd ..
```
## Test the project in the cloud
You can use the gateway created in Section 8 to access the all-cities-weather-service directly.
>💡__Note:__ the trailing slash (`/`) is not optional.
```bash
https://<Your gateway URL>/ALL-CITIES-WEATHER-SERVICE/
```
You should get the JSON output with the weather for all the cities:
```json
[{"city":"Paris, France","description":"It's always sunny on Azure Spring Cloud","icon":"weather-sunny"},
{"city":"London, UK","description":"It's always sunny on Azure Spring Cloud","icon":"weather-sunny"}]
```
---
⬅️ Previous guide: [11 - Configure CI/CD](../11-configure-ci-cd/README.md)
➡️ Next guide: [Conclusion](../99-conclusion/README.md)

Просмотреть файл

@ -1,31 +1,32 @@
# Conclusion
# 总结
**本教程是[Azure Spring Cloud 培训](../README.md)系列之一**
__This guide is part of the [Azure Spring Cloud training](../README.md)__
---
## Cleaning up
## 清理
Unless you plan to perform additional tasks with the Azure resources from the workshop (such as tutorials referenced below), it is important to destroy the resources that we created for it to avoid the cost of keeping them provisioned.
除非您想要使用Workshop的 Azure 资源执行其他任务(如下面引用的教程),否则必须清理我们创建的资源,以避免产生不必要的成本。
The easiest way to do this is to delete the entire resource group.
最简单的方法是删除整个资源组。
>🛑 Substitute the name of your resource group for `$AZ_RESOURCE_GROUP` below:
> 🛑将资源组的名称替换为`$AZ_RESOURCE_GROUP`下面:
```bash
az group delete -g "$AZ_RESOURCE_GROUP" --yes --no-wait
```
## Additional Resources
## 其他资源
As an addendum to this workshop, consider taking the [tutorial on using alerts and action groups with Azure Spring Cloud](https://docs.microsoft.com/azure/spring-cloud/spring-cloud-tutorial-alerts-action-groups/?WT.mc_id=azurespringcloud-github-judubois) to detect and respond to abnormal conditions.
作为本Workshop的附加练习建议完成[使用带有 Azure Spring Cloud的警报和Action Group的教程](https://docs.microsoft.com/azure/spring-cloud/spring-cloud-tutorial-alerts-action-groups/?WT.mc_id=azurespringcloud-github-judubois) 来实现检测和响应异常情况。
Also, check out our tutorial to [Deploy Azure Spring Cloud a virtual network](https://docs.microsoft.com/azure/spring-cloud/spring-cloud-tutorial-deploy-in-azure-virtual-network).
此外,请查看我们的教程[部署Azure Spring Cloud到虚拟网络](https://docs.microsoft.com/azure/spring-cloud/spring-cloud-tutorial-deploy-in-azure-virtual-network).
Have a look through the [Azure Spring Cloud documentation](https://docs.microsoft.com/azure/spring-cloud/?WT.mc_id=azurespringcloud-github-judubois) for more quickstarts, tutorials, and reference materials.
也可以通过[Azure Spring Cloud文档](https://docs.microsoft.com/azure/spring-cloud/)来学习更多快速开始、教程和参考材料。
Find more about the monitoring power for [Spring Cloud with Application Insights](https://docs.microsoft.com/en-us/azure/spring-cloud/spring-cloud-howto-application-insights?WT.mc_id=java-13165-sakriema).
了解更多有关监控能力的 - [带应用洞察的Spring Cloud](https://docs.microsoft.com/en-us/azure/spring-cloud/spring-cloud-howto-application-insights?WT.mc_id=java-13165-sakriema).
---
⬅️ Previous guide: [12 - Making Microservices Talk To Each Other](../12-making-microservices-talk-to-each-other/README.md)
⬅️上一个教程:[12 - 微服务间的相互调用](../12-making-microservices-talk-to-each-other/README.md)

Просмотреть файл

@ -0,0 +1,31 @@
# Conclusion
__This guide is part of the [Azure Spring Cloud training](../README.md)__
---
## Cleaning up
Unless you plan to perform additional tasks with the Azure resources from the workshop (such as tutorials referenced below), it is important to destroy the resources that we created for it to avoid the cost of keeping them provisioned.
The easiest way to do this is to delete the entire resource group.
>🛑 Substitute the name of your resource group for `$AZ_RESOURCE_GROUP` below:
```bash
az group delete -g "$AZ_RESOURCE_GROUP" --yes --no-wait
```
## Additional Resources
As an addendum to this workshop, consider taking the [tutorial on using alerts and action groups with Azure Spring Cloud](https://docs.microsoft.com/azure/spring-cloud/spring-cloud-tutorial-alerts-action-groups/?WT.mc_id=azurespringcloud-github-judubois) to detect and respond to abnormal conditions.
Also, check out our tutorial to [Deploy Azure Spring Cloud a virtual network](https://docs.microsoft.com/azure/spring-cloud/spring-cloud-tutorial-deploy-in-azure-virtual-network).
Have a look through the [Azure Spring Cloud documentation](https://docs.microsoft.com/azure/spring-cloud/?WT.mc_id=azurespringcloud-github-judubois) for more quickstarts, tutorials, and reference materials.
Find more about the monitoring power for [Spring Cloud with Application Insights](https://docs.microsoft.com/en-us/azure/spring-cloud/spring-cloud-howto-application-insights?WT.mc_id=java-13165-sakriema).
---
⬅️ Previous guide: [12 - Making Microservices Talk To Each Other](../12-making-microservices-talk-to-each-other/README.md)

Просмотреть файл

@ -12,11 +12,11 @@ Language
## 友情提示
> 这不是官方文件,而是第三方提供的培训。
> 这不是官方产品组提供的培训,而是第三方提供的培训。
> 这是一次动手培训,它将大量使用命令行cli。这个想法为了是快速编码和熟悉平台从一个简单的演示开始到更复杂的例子。
> 这是一次动手培训,它将大量使用命令行CLI。这样是为了快速编码和熟悉平台从一个简单的演示开始到更复杂的例子。
> 完成所有教程后,您应该对 Azure Spring Cloud提供的一切有相当好的了解。
> 完成所有教程后,您应该对Azure Spring Cloud提供的功能有比较好的了解。
## 符号说明

Просмотреть файл

@ -0,0 +1,100 @@
---
page_type: sample
languages:
- java
---
# Azure Spring Cloud training
You will find here a full workshop on Azure Spring Cloud, including guides and demos.
This lab is based on a public workshop created by [Julien Dubois](https://twitter.com/juliendubois) and available for free to everyone, under the [MIT license](LICENSE.txt).
## What you should expect
This is not the official documentation but an opinionated training.
It is a hands-on training, and it will use the command line extensively. The idea is to get coding very quickly and play with the platform, from a simple demo to far more complex examples.
After completing all the guides, you should have a fairly good understanding of everything that Azure Spring Cloud offers.
## Symbols
>🛑 - __Manual Modification Required__. When this symbol appears in front of one or more commands, you will need to modify the commands as indicated prior to running them.
>🚧 - __Preview-specific__. This symbol indicates steps that are only necessary while Azure Spring Cloud is in preview.
>💡 - __Frustration Avoidance Tip__. These will help you avoid potential pitfalls.
## [00 - Prerequisites and Setup](00-setup-your-environment/README.md)
Prerequisites and environment setup.
## [01 - Create an Azure Spring Cloud cluster](01-create-an-azure-spring-cloud-instance/README.md)
Basics on creating a cluster and configuring the CLI to work efficiently.
## [02 - Build a simple Spring Boot microservice](02-build-a-simple-spring-boot-microservice/README.md)
Build the simplest possible Spring Boot microservice using the Spring Initializer.
## [03 - Configure application logs](03-configure-monitoring/README.md)
Access Spring Boot applications logs to understand common issues.
## [04 - Configure a Spring Cloud Config server](04-configure-a-spring-cloud-config-server/README.md)
Configure a [Spring Cloud Config Server](https://cloud.spring.io/spring-cloud-config), that will be entirely managed and supported by Azure Spring Cloud, to be used by Spring Boot microservices.
## [05 - Build a Spring Boot microservice using Spring Cloud features](05-build-a-spring-boot-microservice-using-spring-cloud-features/README.md)
Build a Spring Boot microservice that is cloud-enabled: it uses a Spring Cloud Service Registry and a [Spring Cloud Config Server](https://cloud.spring.io/spring-cloud-config) which are both managed and supported by Azure Spring Cloud.
## [06 - Build a reactive Spring Boot microservice using Cosmos DB](06-build-a-reactive-spring-boot-microservice-using-cosmosdb/README.md)
Build a reactive Spring Boot microservice, that uses the [Spring reactive stack](https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html) and is bound to a [Cosmos DB database](https://docs.microsoft.com/en-us/azure/cosmos-db/?WT.mc_id=azurespringcloud-github-judubois) in order to access a globally-distributed database with optimum performance.
## [07 - Build a Spring Boot microservice using MySQL](07-build-a-spring-boot-microservice-using-mysql/README.md)
Build a classical Spring Boot application that uses JPA to access a [MySQL database managed by Azure](https://docs.microsoft.com/en-us/azure/mysql/?WT.mc_id=azurespringcloud-github-judubois).
## [08 - Build a Spring Cloud Gateway](08-build-a-spring-cloud-gateway/README.md)
Build a [Spring Cloud Gateway](https://spring.io/projects/spring-cloud-gateway) to route HTTP requests to the correct Spring Boot microservices.
## [09 - Putting it all together, a complete microservice stack](09-putting-it-all-together-a-complete-microservice-stack/README.md)
Use a front-end to access graphically our complete microservice stack. Monitor our services with Azure Spring Cloud's distributed tracing mechanism and scale our services depending on our needs.
## [10 - Blue/Green deployment](10-blue-green-deployment/README.md)
Deploy new versions of applications in a staging environment and switch between staging and production with Azure Spring Cloud.
## [11 - Configure CI/CD](11-configure-ci-cd/README.md)
Configure a Continuous Integration / Continuous Deployment platform using GitHub Actions, so our Spring Boot microservices are automatically deployed.
## [12 - Making Microservices Talk to Each Other](12-making-microservices-talk-to-each-other/README.md)
Creating a microservice that talks to other microservices.
## [Conclusion](99-conclusion/README.md)
---
## Legal Notices
Microsoft and any contributors grant you a license to the Microsoft documentation and other content
in this repository under the [Creative Commons Attribution 4.0 International Public License](https://creativecommons.org/licenses/by/4.0/legalcode),
see the [LICENSE](LICENSE) file, and grant you a license to any code in the repository under the [MIT License](https://opensource.org/licenses/MIT), see the
[LICENSE-CODE](LICENSE-CODE) file.
Microsoft, Windows, Microsoft Azure and/or other Microsoft products and services referenced in the documentation
may be either trademarks or registered trademarks of Microsoft in the United States and/or other countries.
The licenses for this project do not grant you rights to use any Microsoft names, logos, or trademarks.
Microsoft's general trademark guidelines can be found at http://go.microsoft.com/fwlink/?LinkID=254653.
Privacy information can be found at https://privacy.microsoft.com/en-us/
Microsoft and any contributors reserve all other rights, whether under their respective copyrights, patents,
or trademarks, whether by implication, estoppel or otherwise.

Просмотреть файл

@ -0,0 +1,10 @@
::for loop test
@echo off
for %%a in (00, 06,07,08,09,10,11,12,99) do (
cd %%a*
if exist README.md (echo "skipped "%%a)
if not exist README.md (if exist README_en.md md-translator translate --src README_en.md --dest README.md --to zh)
cd ..
)
exit /b