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 監視頁面,可看到日誌信息:


 

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