您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

快速入门:将遥测数据发送到 Azure IoT 中心并使用 Java 应用程序读取它Quickstart: Send telemetry to an Azure IoT hub and read it with a Java application

在本快速入门中,我们将遥测数据发送到 Azure IoT 中心并使用 Java 应用程序读取它。In this quickstart, you send telemetry to Azure IoT Hub and read it with a Java application. IoT 中心是一项 Azure 服务,用于将大量遥测数据从 IoT 设备引入云中进行存储或处理。IoT Hub is an Azure service that enables you to ingest high volumes of telemetry from your IoT devices into the cloud for storage or processing. 本快速入门使用两个预先编写的 Java 应用程序:一个用于发送遥测数据,一个用于读取中心的遥测数据。This quickstart uses two pre-written Java applications: one to send the telemetry and one to read the telemetry from the hub. 运行这两个应用程序前,请先创建 IoT 中心并在中心注册设备。Before you run these two applications, you create an IoT hub and register a device with the hub.


  • 具有活动订阅的 Azure 帐户。An Azure account with an active subscription. 免费创建一个Create one for free.

  • Java SE 开发工具包 8。Java SE Development Kit 8. 针对 Azure 和 Azure Stack 的 Java 长期支持中的“长期支持”下选择“Java 8”。In Java long-term support for Azure and Azure Stack, under Long-term support, select Java 8.

    可以使用以下命令验证开发计算机上 Java 的当前版本:You can verify the current version of Java on your development machine using the following command:

    java -version
  • Apache Maven 3Apache Maven 3.

    可以使用以下命令验证开发计算机上 Maven 的当前版本:You can verify the current version of Maven on your development machine using the following command:

    mvn --version
  • 使用 azure-iot-samples-java 存储库页上的“代码”按钮下载或克隆 azure-iot-samples-java 存储库。Download or clone the azure-iot-samples-java repository using the Code button on the azure-iot-samples-java repository page.

    本文会使用存储库中的 simulated-deviceread-d2c-messages 示例。This article uses the simulated-device and read-d2c-messages samples from the repository.

  • 端口 8883 在防火墙中处于打开状态。Port 8883 open in your firewall. 本快速入门中的设备示例使用 MQTT 协议,该协议通过端口 8883 进行通信。The device sample in this quickstart uses MQTT protocol, which communicates over port 8883. 在某些公司和教育网络环境中,此端口可能被阻止。This port may be blocked in some corporate and educational network environments. 有关解决此问题的更多信息和方法,请参阅连接到 IoT 中心(MQTT)For more information and ways to work around this issue, see Connecting to IoT Hub (MQTT).

  • Azure Cloud Shell 中使用 Bash 环境。Use the Bash environment in Azure Cloud Shell.

    在新窗口中启动 Cloud ShellLaunch Cloud Shell in a new window

  • 如果需要,请安装 Azure CLI 来运行 CLI 参考命令。If you prefer, install the Azure CLI to run CLI reference commands.

    • 如果使用的是本地安装,请使用 az login 命令登录到 Azure CLI。If you're using a local installation, sign in to the Azure CLI by using the az login command. 若要完成身份验证过程,请遵循终端中显示的步骤。To finish the authentication process, follow the steps displayed in your terminal. 有关其他登录选项,请参阅登录 Azure CLIFor additional sign-in options, see Sign in with the Azure CLI.

    • 出现提示时,请在首次使用时安装 Azure CLI 扩展。When you're prompted, install Azure CLI extensions on first use. 有关扩展详细信息,请参阅使用 Azure CLI 的扩展For more information about extensions, see Use extensions with the Azure CLI.

    • 运行 az version 以查找安装的版本和依赖库。Run az version to find the version and dependent libraries that are installed. 若要升级到最新版本,请运行 az upgradeTo upgrade to the latest version, run az upgrade.


本文使用最新版本的 Azure IoT 扩展(称为 azure-iot)。This article uses the newest version of the Azure IoT extension, called azure-iot. 旧版本称为 azure-cli-iot-ext。只应同时安装有一个版本。The legacy version is called azure-cli-iot-ext.You should only have one version installed at a time. 可以使用命令 az extension list 来验证当前安装的扩展。You can use the command az extension list to validate the currently installed extensions.

使用 az extension remove --name azure-cli-iot-ext 可删除扩展的旧版本。Use az extension remove --name azure-cli-iot-ext to remove the legacy version of the extension.

使用 az extension add --name azure-iot 可添加扩展的新版本。Use az extension add --name azure-iot to add the new version of the extension.

若要查看已安装了哪些扩展,请使用 az extension listTo see what extensions you have installed, use az extension list.

创建 IoT 中心Create an IoT hub

此部分介绍如何使用 Azure 门户创建 IoT 中心。This section describes how to create an IoT hub using the Azure portal.

  1. 登录 Azure 门户Sign in to the Azure portal.

  2. 从 Azure 主页中选择“+ 创建资源”按钮,然后在“搜索市场”字段中输入“IoT 中心”。From the Azure homepage, select the + Create a resource button, and then enter IoT Hub in the Search the Marketplace field.

  3. 在搜索结果中选择“IoT 中心”,然后选择“创建” 。Select IoT Hub from the search results, and then select Create.

  4. 在“基本信息”选项卡上,按如下所示填写字段:On the Basics tab, complete the fields as follows:

    • 订阅:选择要用于中心的订阅。Subscription: Select the subscription to use for your hub.

    • 资源组:选择一个资源组或新建一个资源组。Resource Group: Select a resource group or create a new one. 若要新建资源组,请选择“新建”并填写要使用的名称。To create a new one, select Create new and fill in the name you want to use. 若要使用现有的资源组,请选择它。To use an existing resource group, select that resource group. 有关详细信息,请参阅管理 Azure 资源管理器资源组For more information, see Manage Azure Resource Manager resource groups.

    • 区域:选择中心所在的区域。Region: Select the region in which you want your hub to be located. 选择最靠近你的位置。Select the location closest to you. 某些功能(如 IoT 中心设备流)仅适用于特定区域。Some features, such as IoT Hub device streams, are only available in specific regions. 对于这些受限功能,你必须选择受支持的区域之一。For these limited features, you must select one of the supported regions.

    • IoT 中心名称:输入中心的名称。IoT Hub Name: Enter a name for your hub. 该名称必须全局唯一。This name must be globally unique.


    由于 IoT 中心将作为 DNS 终结点公开可发现,因此请务必避免在命名它时输入任何敏感信息或个人身份信息。Because the IoT hub will be publicly discoverable as a DNS endpoint, be sure to avoid entering any sensitive or personally identifiable information when you name it.

    在 Azure 门户中创建中心。

  5. 在完成时选择“下一步:网络”,继续创建中心。Select Next: Networking to continue creating your hub.

    选择可以连接到 IoT 中心的终结点。Choose the endpoints that can connect to your IoT Hub. 你可以选择默认设置“公共终结点(所有网络)”,也可选择“公共终结点(选定的 IP 范围)”或“专用终结点” 。You can select the default setting Public endpoint (all networks), or choose Public endpoint (selected IP ranges), or Private endpoint. 接受此示例的默认设置。Accept the default setting for this example.


  6. 在完成时选择“下一步:管理”,继续创建中心。Select Next: Management to continue creating your hub.

    使用 Azure 门户为新的中心设置大小和规模。

    可在此处接受默认设置。You can accept the default settings here. 如果需要,可以修改以下任何字段:If desired, you can modify any of the following fields:

    • 定价和缩放层:选择的层。Pricing and scale tier: Your selected tier. 可以根据你需要的功能数以及每天通过解决方案发送的消息数从多个层级中进行选择。You can choose from several tiers, depending on how many features you want and how many messages you send through your solution per day. 免费层适用于测试和评估。The free tier is intended for testing and evaluation. 允许 500 台设备连接到中心,每天最多可传输 8,000 条消息。It allows 500 devices to be connected to the hub and up to 8,000 messages per day. 每个 Azure 订阅可以在免费层中创建一个 IoT 中心。Each Azure subscription can create one IoT hub in the free tier.

      如果正在完成 IoT 中心设备流的快速入门,请选择免费层。If you are working through a Quickstart for IoT Hub device streams, select the free tier.

    • IoT 中心单元:每日每单位允许的消息数取决于中心的定价层。IoT Hub units: The number of messages allowed per unit per day depends on your hub's pricing tier. 例如,如果希望中心支持 700,000 条消息引入,请选择两个 S1 层单位。For example, if you want the hub to support ingress of 700,000 messages, you choose two S1 tier units. 有关其他层选项的详细信息,请参阅选择合适的 IoT 中心层For details about the other tier options, see Choosing the right IoT Hub tier.

    • Defender for IoT:启用此功能可为 IoT 和设备添加额外的一层威胁防护。Defender for IoT: Turn this on to add an extra layer of threat protection to IoT and your devices. 此选项不可用于免费层的中心。This option is not available for hubs in the free tier. 有关此功能的详细信息,请参阅适用于 IoT 的 Azure 安全中心For more information about this feature, see Azure Security Center for IoT.

    • 高级设置 > 设备到云的分区:此属性将设备到云消息与这些消息的同步读取器数目相关联。Advanced Settings > Device-to-cloud partitions: This property relates the device-to-cloud messages to the number of simultaneous readers of the messages. 大多数中心只需要 4 个分区。Most hubs need only four partitions.

  7. 在完成时选择“下一步:标记”继续到下一屏幕。Select Next: Tags to continue to the next screen.

    标记是名称/值对。Tags are name/value pairs. 可以为多个资源和资源组分配相同的标记,以便对资源进行分类并合并计费。You can assign the same tag to multiple resources and resource groups to categorize resources and consolidate billing. 有关详细信息,请参阅使用标记来组织 Azure 资源For more information, see Use tags to organize your Azure resources.

    使用 Azure 门户为中心分配标记。

  8. 在完成时选择“下一步:查看+创建”可查看选择。Select Next: Review + create to review your choices. 你会看到类似于此屏幕的内容,但其中包含创建中心时选择的值。You see something similar to this screen, but with the values you selected when creating the hub.


  9. 选择“创建”以创建新的中心。Select Create to create your new hub. 创建中心需要几分钟时间。Creating the hub takes a few minutes.

注册设备Register a device

必须先将设备注册到 IoT 中心,然后该设备才能进行连接。A device must be registered with your IoT hub before it can connect. 在本快速入门中,将使用 Azure Cloud Shell 来注册模拟设备。In this quickstart, you use the Azure Cloud Shell to register a simulated device.

  1. 在 Azure Cloud Shell 中运行以下命令,以创建设备标识。Run the following command in Azure Cloud Shell to create the device identity.

    YourIoTHubName:将下面的占位符替换为你为 IoT 中心选择的名称。YourIoTHubName: Replace this placeholder below with the name you chose for your IoT hub.

    MyJavaDevice:这是所注册的设备的名称。MyJavaDevice: This is the name of the device you're registering. 建议使用 MyJavaDevice,如图所示。It's recommended to use MyJavaDevice as shown. 如果为设备选择不同名称,则可能还需要在本文中从头至尾使用该名称,并在运行示例应用程序之前在其中更新设备名称。If you choose a different name for your device, you'll also need to use that name throughout this article, and update the device name in the sample applications before you run them.

    az iot hub device-identity create --hub-name {YourIoTHubName} --device-id MyJavaDevice
  2. 在 Azure Cloud Shell 中运行以下命令,以获取刚注册设备的 设备连接字符串Run the following command in Azure Cloud Shell to get the device connection string for the device you just registered:

    YourIoTHubName:将下面的占位符替换为你为 IoT 中心选择的名称。YourIoTHubName: Replace this placeholder below with the name you chose for your IoT hub.

    az iot hub device-identity connection-string show --hub-name {YourIoTHubName} --device-id MyJavaDevice --output table

    记下如下所示的设备连接字符串:Make a note of the device connection string, which looks like:


    稍后会在快速入门中用到此值。You'll use this value later in the quickstart.

  3. 还需要使用与事件中心兼容的终结点、与事件中心兼容的路径和 IoT 中心的服务主密钥,确保后端应用程序能连接到 IoT 中心并检索消息 。You also need the Event Hubs-compatible endpoint, Event Hubs-compatible path, and service primary key from your IoT hub to enable the back-end application to connect to your IoT hub and retrieve the messages. 以下命令可检索 IoT 中心的这些值:The following commands retrieve these values for your IoT hub:

    YourIoTHubName:将下面的占位符替换为你为 IoT 中心选择的名称。YourIoTHubName: Replace this placeholder below with the name you chose for your IoT hub.

    az iot hub show --query properties.eventHubEndpoints.events.endpoint --name {YourIoTHubName}
    az iot hub show --query properties.eventHubEndpoints.events.path --name {YourIoTHubName}
    az iot hub policy show --name service --query primaryKey --hub-name {YourIoTHubName}

    记下这三个值,稍后会在快速入门中用到这些值。Make a note of these three values, which you'll use later in the quickstart.

发送模拟遥测数据Send simulated telemetry

模拟设备应用程序会连接到 IoT 中心上特定于设备的终结点,并发送模拟的温度和湿度遥测数据。The simulated device application connects to a device-specific endpoint on your IoT hub and sends simulated temperature and humidity telemetry.

  1. 在本地终端窗口中,导航到示例 Java 项目的根文件夹。In a local terminal window, navigate to the root folder of the sample Java project. 然后导航到 iot-hub\Quickstarts\simulated-device 文件夹。Then navigate to the iot-hub\Quickstarts\simulated-device folder.

  2. 在所选文本编辑器中打开 src/main/java/com/microsoft/docs/iothub/samples/SimulatedDevice.java 文件。Open the src/main/java/com/microsoft/docs/iothub/samples/SimulatedDevice.java file in a text editor of your choice.

    connString 变量的值替换为之前记下的设备连接字符串。Replace the value of the connString variable with the device connection string you made a note of earlier. 然后将更改保存到 SimulatedDevice.javaThen save your changes to SimulatedDevice.java.

    public class SimulatedDevice {
      // The device connection string to authenticate the device with your IoT hub.
      // Using the Azure CLI:
      // az iot hub device-identity show-connection-string --hub-name {YourIoTHubName} --device-id MyJavaDevice --output table
      //private static String connString = "{Your device connection string here}";    
      private static String connString = "HostName={YourIoTHubName}.azure-devices.net;DeviceId=MyJavaDevice;SharedAccessKey={YourSharedAccessKey}";    
  3. 在本地终端窗口中,运行以下命令以安装所需的库,并生成模拟设备应用程序:In the local terminal window, run the following commands to install the required libraries and build the simulated device application:

    mvn clean package
  4. 在本地终端窗口中,运行以下命令,以便运行模拟设备应用程序:In the local terminal window, run the following commands to run the simulated device application:

    java -jar target/simulated-device-1.0.0-with-deps.jar

    以下屏幕截图显示了模拟设备应用程序将遥测数据发送到 IoT 中心后的输出:The following screenshot shows the output as the simulated device application sends telemetry to your IoT hub:

    设备发送到 IoT 中心的遥测的输出

从中心读取遥测数据Read the telemetry from your hub

后端应用程序会连接到 IoT 中心上的服务端“事件”终结点。The back-end application connects to the service-side Events endpoint on your IoT Hub. 应用程序会接收模拟设备发送的设备到云的消息。The application receives the device-to-cloud messages sent from your simulated device. IoT 中心后端应用程序通常在云中运行,接收和处理设备到云的消息。An IoT Hub back-end application typically runs in the cloud to receive and process device-to-cloud messages.

  1. 在另一个本地终端窗口中,导航到示例 Java 项目的根文件夹。In another local terminal window, navigate to the root folder of the sample Java project. 然后导航到 iot-hub\Quickstarts\read-d2c-messages 文件夹。Then navigate to the iot-hub\Quickstarts\read-d2c-messages folder.

  2. 在所选文本编辑器中打开 src/main/java/com/microsoft/docs/iothub/samples/ReadDeviceToCloudMessages.java 文件。Open the src/main/java/com/microsoft/docs/iothub/samples/ReadDeviceToCloudMessages.java file in a text editor of your choice. 更新以下变量并保存对文件所做的更改。Update the following variables and save your changes to the file.

    变量Variable Value
    EVENT_HUBS_COMPATIBLE_ENDPOINT 将变量的值替换为之前记下的与事件中心兼容的终结点。Replace the value of the variable with the Event Hubs-compatible endpoint you made a note of earlier.
    EVENT_HUBS_COMPATIBLE_PATH 将变量的值替换为之前记下的与事件中心兼容的路径。Replace the value of the variable with the Event Hubs-compatible path you made a note of earlier.
    IOT_HUB_SAS_KEY 将变量的值替换为之前记下的服务主密钥。Replace the value of the variable with the service primary key you made a note of earlier.
    public class ReadDeviceToCloudMessages {
      private static final String EH_COMPATIBLE_CONNECTION_STRING_FORMAT = "Endpoint=%s/;EntityPath=%s;"
          + "SharedAccessKeyName=%s;SharedAccessKey=%s";
      // az iot hub show --query properties.eventHubEndpoints.events.endpoint --name {your IoT Hub name}
      private static final String EVENT_HUBS_COMPATIBLE_ENDPOINT = "{your Event Hubs compatible endpoint}";
      // az iot hub show --query properties.eventHubEndpoints.events.path --name {your IoT Hub name}
      private static final String EVENT_HUBS_COMPATIBLE_PATH = "{your Event Hubs compatible name}";
      // az iot hub policy show --name service --query primaryKey --hub-name {your IoT Hub name}
      private static final String IOT_HUB_SAS_KEY = "{your service primary key}";    
  3. 在本地终端窗口中运行以下命令,以安装所需的库并生成后端应用程序:In the local terminal window, run the following commands to install the required libraries and build the back-end application:

    mvn clean package
  4. 在本地终端窗口中,运行以下命令,以便运行终端应用程序:In the local terminal window, run the following commands to run the back-end application:

    java -jar target/read-d2c-messages-1.0.0-with-deps.jar

    以下屏幕截图显示了后端应用程序接收模拟设备发送到 IoT 中心的遥测数据后的输出:The following screenshot shows the output as the back-end application receives telemetry sent by the simulated device to the hub:

    后端应用程序接收发送到 IoT 中心的遥测时的输出

清理资源Clean up resources

如果想要继续学习下一篇建议的文章,可以保留已创建的资源,以便重复使用。If you will be continuing to the next recommended article, you can keep the resources you've already created and reuse them.

否则,可删除本文中创建的 Azure 资源,避免收费。Otherwise, you can delete the Azure resources created in this article to avoid charges.


删除资源组的操作不可逆。Deleting a resource group is irreversible. 资源组以及包含在其中的所有资源将被永久删除。The resource group and all the resources contained in it are permanently deleted. 请确保不会意外删除错误的资源组或资源。Make sure that you do not accidentally delete the wrong resource group or resources. 如果在现有的包含要保留资源的资源组中创建了 IoT 中心,则只删除 IoT 中心资源本身,而不要删除资源组。If you created the IoT Hub inside an existing resource group that contains resources you want to keep, only delete the IoT Hub resource itself instead of deleting the resource group.

若要按名称删除资源组,请执行以下操作:To delete a resource group by name:

  1. 登录到 Azure 门户,然后选择“资源组”。 Sign in to the Azure portal and select Resource groups.

  2. 在“按名称筛选”文本框中,键入包含 IoT 中心的资源组的名称。In the Filter by name textbox, type the name of the resource group containing your IoT Hub.

  3. 在结果列表中的资源组右侧,选择“...”,然后选择“删除资源组” 。To the right of your resource group in the result list, select ... then Delete resource group.


  4. 系统会要求确认是否删除资源组。You will be asked to confirm the deletion of the resource group. 再次键入资源组的名称进行确认,然后选择“删除” 。Type the name of your resource group again to confirm, and then select Delete. 片刻之后,将会删除该资源组及其包含的所有资源。After a few moments, the resource group and all of its contained resources are deleted.

后续步骤Next steps

本快速入门设置了 IoT 中心、注册了设备、使用 Java 应用程序发送了模拟遥测数据到中心,并使用简单的后端应用程序读取中心的遥测数据。In this quickstart, you set up an IoT hub, registered a device, sent simulated telemetry to the hub using a Java application, and read the telemetry from the hub using a simple back-end application.

若要了解如何从后端应用程序控制模拟设备,请继续阅读下一快速入门教程。To learn how to control your simulated device from a back-end application, continue to the next quickstart.