プリンキピア

第12章クラウドネイティブアプリケーション開発

Create, Build, and Deploy the FaaS Consumer FunctionFaaSの消費側の関数を作成・ビルド・配備する
Now that the FaaS producer function is built and deployed, the next step is to create an Azure FaaS function project for the FaaS consumer function. Like the FaaS producer function, a few resources need to be created for the FaaS consumer function. A storage account is created. The FaaS consumer function needs to connect to the Azure event hub. The FaaS consumer function also needs to connect to the Azure Cosmos DB datastore. The FaaS consumer function is built as a maven project and then deployed as an Azure Function App.
英語のヒント
FaaSの生成側の関数のビルドと配備が終わったので、次は消費側の関数用に、Azure FaaS関数のプロジェクトを作る。生成側と同様、いくつかの資源を作る必要がある。ストレージアカウントを作り、消費側の関数をAzureイベントハブとAzure Cosmos DBのデータストアへ接続できるようにする。関数をMavenプロジェクトとしてビルドし、Azure Function Appとして配備する。
1. Run the commands below to create a storage account and the FaaS consumer function.
1. 次のコマンドで、ストレージアカウントとFaaSの消費側の関数を作る。
az storage account create\
  --resource-group $RESOURCE_GROUP\
  --name $STORAGE_ACCOUNT"c"\
  --sku Standard_LRS

az functionapp create\
  --resource-group $RESOURCE_GROUP\
  --name $FUNCTION_APP"-c"\
  --storage-account $STORAGE_ACCOUNT"c"\
  --consumption-plan-location $LOCATION\
  --runtime java\
  --functions-version 4
2. Use the commands below to obtain the connection strings for the storage account and the datastore. These values, as well as the datastore information, are required for the consumer function.
英語のヒント
2. 次のコマンドで、ストレージアカウントとデータストアの接続文字列を取得する。これらの値は、データストアの情報とともに、消費側の関数に必要である。
AZURE_WEB_JOBS_STORAGE=$(\
az storage account show-connection-string\
  --resource-group $RESOURCE_GROUP\
  --name $STORAGE_ACCOUNT"c"\
  --query connectionString \
  --output tsv)

COSMOS_DB_CONNECTION_STRING=$(\
az cosmosdb keys list\
  --resource-group $RESOURCE_GROUP\
  --name $COSMOS_DB_ACCOUNT\
  --type connection-strings\
  --query 'connectionStrings[0].connectionString'\
  --output tsv)
3. Run the command below to obtain the event hub connection string.
3. 次のコマンドで、イベントハブの接続文字列を取得する。
EVENT_HUB_CONNECTION_STRING=$(\
az eventhubs eventhub authorization-rule keys list\
  --resource-group $RESOURCE_GROUP\
  --name $EVENT HUB_AUTHORIZATION_RULE\
  --eventhub-name $EVENT_HUB_NAME\
  --namespace-name $EVENT_HUB_NAMESPACE\
  --query primaryConnectionString\
  --output tsv)
4. Run the commands below to display the connection strings that were created in the previous steps. Make a note of these connection strings as they will be used later.
4. 次のコマンドで、これまでの手順で作った接続文字列を表示する。後で使うため、控えておく。
echo $AZURE_WEB_JOBS_STORAGE
echo $EVENT_HUB_CONNECTION_STRING
echo $COSMOS_DB_CONNECTION_STRING
5. The connection strings that were generated for the Azure Web Jobs Storage, Event Hub, and Azure Cosmos DB datastore in the previous step need to be added as application settings to the Azure Function App account in the command. Run the command below with these values inserted to create the Function App. A notification to the console indicates that the Function App was built successfully.
5. 前の手順で生成したAzure Web Jobs Storage、Event Hub、Azure Cosmos DBデータストアの接続文字列を、コマンド内のAzure Function Appアカウントに、アプリケーション設定として追加する必要がある。これらの値を入れた次のコマンドを実行し、Function Appを作る。コンソールへの通知が、Function Appのビルド成功を示す。
az functionapp config appsettings set\
  --resource-group $RESOURCE_GROUP\
  --name $FUNCTION_APP"-c"\
  --settings\
    AzureWebJobsStorage=$AZURE_WEB_JOBS_STORAGE\
    EventHubConnectionString=$EVENT_HUB_CONNECTION_STRING\
    CosmosDBConnectionString=$COSMOS_DB_CONNECTION_STRING
Build and Deploy the FaaS Consumer Function
FaaSの消費側の関数をビルドして配備する
Now that the Azure resources, such as the event hub, Azure Function App, Storage account, and Azure Cosmos DB, have been created and configured, the next step is to create an Azure FaaS function project for the FaaS producer function. Maven is used to build the project.
イベントハブ、Azure Function App、ストレージアカウント、Azure Cosmos DBなどのAzure資源が作成・設定できたので、次はFaaSの生成側の関数用に、Azure FaaS関数のプロジェクトを作る。プロジェクトのビルドにはMavenを使う。
1. Run the command below to create the function project for the FaaS consumer function. The telemetry-functions-consumer/ directory is generated along with the files for the project.
1. 次のコマンドで、FaaSの消費側の関数用のプロジェクトを作る。telemetry-functions-consumer/ディレクトリーが、プロジェクトのファイルとともに生成される。
mvn archetype:generate -batch-mode\
  -DarchetypeGroupId=com.microsoft.azure
  -DarchetypeArtifactId=azure-functions-archetype
  -DappName=$FUNCTION_APP"-c" \
  -DresourceGroup=$RESOURCE_GROUP
  -DappRegion=$LOCATION\
  -DappServicePlanName=$LOCATION"plan" \
  -Dgroupid=com.learn \
  -DartifactId=telemetry-functions-consumer
2. Navigate into the telemetry-functions-consumer/ directory. Run the command below to update the local settings for local execution with the command. These settings are added to the local.settings.json file.
英語のヒント
2. telemetry-functions-consumer/ディレクトリーへ移動する。次のコマンドで、ローカル実行用の設定を更新する。設定はlocal.settings.jsonファイルへ加えられる。
func azure functionapp fetch -app-settings \ $FUNCTION_APP”-p”
3. Navigate to the src/main/java/com/learn/ directory. Replace all the code in Function.java with the code shown below. The code declares a Function that establishes connections to the Azure event hub and Azure Cosmos DB.
3. src/main/java/com/learn/ディレクトリーへ移動する。Function.javaの全コードを、次のものへ置き換える。このコードは、AzureイベントハブとAzure Cosmos DBへの接続を確立するFunctionを宣言する。
package com.learn;
import com.learn.TelemetryItem.status;
import com.microsoft.azure.functions.annotation.FunctionName;
import com.microsoft.azure.functions.ExecutionContext;
import com.microsoft.azure.functions.OutputBinding;
import com.microsoft.azure.functions.annotation.Cardinality;
import com.microsoft.azure.functions.annotation.CosmosDBOutput;
import com.microsoft.azure.functions.annotation.EventHubTrigger;

public class Function
{
  @FunctionName("processSensorData")
  public void processSensorData(
  @EventHubTrigger(
  name ="msg",
  eventHubName = "", // blank because the value is included in the connection string
  cardinality = Cardinality.ONE,
  connection = "EventHubConnectionString")
  TelemetryItem item,
  @CosmosDBOutput(
  name = "databaseOutput",
  databaseName ="TelemetryDb",
  collectionName ="TelemetryInfo",
  connectionStringSetting = "Cosmos DB ConnectionString")
  OutputBinding <TelemetryItem> document,
  final ExecutionContext context) {

    context.getLogger().info("Event hub message received: " + item.toString());
    if (item.getPressure() > 30) {
      item.setNormalPressure(false);
    }
    else {
      item.setNormalPressure(true);
    }

    if (item.getTemperature() < 40) {
      item.setTemperatureStatus(status.COOL);
    }
    else if (item.getTemperature() > 90) {
      item.setTemperatureStatus(status.HOT);
    }
    else {
      item.setTemperatureStatus(status.WARM);
    }
    document.setValue(item);
  }
4. Create the file TelemetryItem.java and add the code shown below. The code declares data items that are received from the Azure event bus and stored in the Azure Cosmos DB datastore.
英語のヒント
4. TelemetryItem.javaファイルを作り、次のコードを加える。このコードは、Azureイベントバスから受け取り、Azure Cosmos DBデータストアへ保存するデータ項目を宣言する。
package com.learn;

public class TelemetryItem {
    private String id;
    private double temperature;
    private double pressure;
    private boolean isNormalPressure;
    private status temperatureStatus;
    static enum status {
        COOL,
        WARM,"
        HOT
    }

    public TelemetryItem(double temperature,double pressure) {
        this.temperature = temperature;
        this.pressure = pressure;
    }
    public String getId() {
        return id;
    }
    public double getTemperature() {
        return temperature;
    }
    public double getPressure() {
        return pressure;
    }
    @Override"
    public String toString() {
        return \"TelemetryItem={id=" + id + \",temperature="
            + temperature + ",pressure=" + pressure + "}";
    }
    public boolean isNormalPressure() {
        return isNormalPressure;
    }
    public void setNormalPressure(boolean isNormal) {
        this.isNormalPressure = isNormal;
    }
    public status getTemperatureStatus() {
        return temperatureStatus;
    }
    public void setTemperatureStatus(status temperatureStatus) {
        this.temperatureStatus = temperatureStatus;
    }
}
5. Navigate to the telemetry-functions-consumer/ directory and build the function with the command below. Once the build is complete, a Build Success message is displayed to the console to indicate the build was successful.
5. telemetry-functions-consumer/ディレクトリーへ移動し、次のコマンドで関数をビルドする。完了すると、コンソールにBuild Successメッセージが現れ、ビルド成功を示す。
mvn clean package
6. Run the command below to test if the function runs properly.
6. 次のコマンドで、関数が正しく動くかテストする。
mvn azure-functions:run
7. As mentioned earlier, the FaaS consumer function listens to events of a specific namespace in the Azure event hub and processes and stores them in an Azure Cosmos DB datastore. The events stored in the Azure Cosmos DB datastore can be checked by visiting the Azure Cosmos DB page in the Azure Portal. In the Azure Portal, navigate to the Azure Cosmos DB page. On the left menu, click on Data Explorer, click on the TelemetryInfo tab, and then click on Items expanded from TelemetryInfo to view the data. Data will continue to be sent to the Azure Cosmos DB datastore, which can be viewed in real time.
英語のヒント
7. 先に述べたように、FaaSの消費側の関数は、Azureイベントハブの特定の名前空間でイベントを待ち受け、処理してAzure Cosmos DBデータストアへ保存する。保存されたイベントは、AzureポータルのAzure Cosmos DBページで確認できる。そのページを開き、左側のメニューでData Explorerを選び、TelemetryInfoタブをクリックする。次に、TelemetryInfoを展開してItemsをクリックし、データを見る。データは引き続きデータストアへ送られ、リアルタイムに確認できる。
8. Run the command below to deploy the functions to Azure Functions. Once the deployment completes, a Build Success message appears in the console.
8. 次のコマンドで、関数をAzure Functionsへ配備する。完了すると、コンソールにBuild Successメッセージが現れる。
mvn azure-functions:deploy