SDKでEvent Gridにイベントを発行する

このエントリは2022/05/26現在の情報に基づいています。将来の機能追加や変更に伴い、記載内容との乖離が発生する可能性があります。

先日以下のようなエントリを書いた。

このときついでにSDKでの設定方法も確認したので、その備忘録。

前提条件

  • SDKはJava SDKを利用 (JDK 11)
  • HTTP TriggerのFunctionsで利用
    • 通常、Event Gridにイベント発行する場合にはバインディングを使うが、今回はSDKとManaged Identitiesを使いたかったため。

構成のポイント

以前Functions間の認証にManaged Identityを使うエントリを書いているが、基本的にその流れの通り。

依存関係は以下を指定しておく。

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-identity</artifactId>
    <version>{the latest version}</version>
</dependency>
<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-messaging-eventgrid</artifactId>
    <version>{the latest version}</version>
</dependency>

前回の例ではCloudEventではなく、EventGridEventだったので、EventGridPublisherClientインスタンス生成時に型としてEventGridEventクラスを指定する。Managed Identitiesを使う場合でも、DefaultAzureCredentialインスタンスをCredntialとして渡せばOKなのはこれまでと同様。

EventGridPublisherClient<EventGridEvent> eventEventGridPublisherClient
    = new EventGridPublisherClientBuilder()
    .credential(new DefaultAzureCredentialBuilder().build())
    .endpoint(<Event Grid Topic Endpoint>)
    .buildEventGridEventPublisherClient();

あとはイベントを作成して、Event Gridに発行するのだが、メソッドに渡すイベントはListでなければならない。このあたりはREST APIと類似している(というか、SDK自体がREST APIのWrapperなので仕方ない)。

// Create a CloudEvent with String data
EventGridEvent eventGridEvent = new EventGridEvent(...);

// Even though only one event is sent, events should be packed into List.
List<EventGridEvent> events = List.of(eventGridEvent);

// Without using WithResponse method, try-catch clause should be used for error handling.
Response<Void> response = eventEventGridPublisherClient.sendEventsWithResponse(events, Context.NONE);
funcReturn.setStatusCode(response.getStatusCode());
funcReturn.setMessage(event);

コメントを残す

以下に詳細を記入するか、アイコンをクリックしてログインしてください。

WordPress.com ロゴ

WordPress.com アカウントを使ってコメントしています。 ログアウト /  変更 )

Facebook の写真

Facebook アカウントを使ってコメントしています。 ログアウト /  変更 )

%s と連携中