Azure IoT Hub入门系列 (11)- 10分钟实现Azure Function 通过IoT Hub Trigger处理设备到云的消息(Java)

本文介绍如下:

1.Java 语言和VS Code 开发Azure Functions的准备工作;

2.设备发送遥测消息到 IoT Hub后使用Azure Function 的IoT Hub Trigger 处理遥测消息;

3.使用VS Code 部署Azure Function;

开发语言:Java      开发工具:VS Code

 


本文中涉及到的重点内容包括:

1. Java Functions 开发环境配置;

2. Java Function Event Hub trigger 从systemProperties获取device ID

3.手动安装Azure Functions Core Tools 

4. 本地Function 运行过程中遇到 func.ps1 cannot be loaded because running scripts is disabled on this system.

5.Azure functions 发布后的参数添加

 


视频介绍:

https://www.51azure.cloud/post/2020/6/7/azure-iot-hub-azure-function-iot-hub-trigger-java


图文介绍:

1. Java Functions 开发环境配置;

可参照官网:https://docs.microsoft.com/en-us/azure/azure-functions/functions-create-first-function-vs-code?pivots=programming-language-java#configure-your-environment

主要是安装JDK 和 Maven:

2. Java Function Event Hub trigger 从systemProperties获取device ID

参照官网文档可以获取systemProperties中的属性,比如设备ID:https://docs.microsoft.com/en-us/azure/azure-functions/functions-bindings-event-iot-trigger?tabs=java#event-metadata

参考代码如下:

    @FunctionName("ehprocessor")
public void eventHubProcessor(
  @BindingName("SystemPropertiesArray") Map<String, Object>[] systemProperties,
  @EventHubTrigger(name = "msg",
                  eventHubName = "myeventhubname",
                  connection = "myconnvarname") String message,
       final ExecutionContext context )
       {
          context.getLogger().info(message);       


        String deviceId = (String) systemProperties[0].get("iothub-connection-device-id");

        context.getLogger().info(deviceId);
          //decode/parse message string
        
          
 }

配置文件需修改如下:

其中AzureWebJobsStorage: 新建一个StorageAccount并将连接字符串复制到这里即可

 

其中“myconnvarname” 为自定义的名称,该名称需与java代码中的名称保持一致,值为iot hub 内置的event-hub终结点:

 

值可以在IoT Hub中找到:

 

3. 在本地手动安装 Azure Functions Core Tools:

安装过程可能需要使用VPN。

安装3.0版本Azure Functions Core Tools:https://docs.microsoft.com/en-us/azure/azure-functions/functions-run-local?tabs=windows%2Ccsharp%2Cbash#install-the-azure-functions-core-tools

npm install -g azure-functions-core-tools@3

 

如果上述npm 安装过程太慢,则可以使用如下方式,下载安装最新的版本即可:

https://github.com/Azure/azure-functions-core-tools/releases

4. 本地Function 运行过程中遇到 func.ps1 cannot be loaded because running scripts is disabled on this system.

参照官网:https://docs.microsoft.com/en-us/azure/azure-functions/functions-create-first-function-vs-code?pivots=programming-language-java#configure-your-environment

 

如果遇到错误func.ps1 cannot be loaded because running scripts is disabled on this system.

在power shell中运行如下命令:

Set-ExecutionPolicy unrestricted

 

5.Azure functions 发布后的参数添加

在本地开启一个Device 向IoT Hub发送遥测消息,如下图表示本地执行成功:

发布Functions: ctrl+shift+p

 

在云中的Functions 添加IoT Hub的内置Event Hub终结点的配置文件:

具体配置 需与local.settings.json 保持一致:

 

在Functions 监视页面,可看到日志信息:


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章