このエントリは2020/10/23現在の情報に基づいています。将来の機能追加や変更に伴い、記載内容との乖離が発生する可能性があります。
先日(かなり日があいたが)、Event GridでCloudEventsを扱うエントリを記載した。
CloudEventsを使う
https://logico-jp.io/2020/09/06/use-cloudevents-schema-in-azure-event-grid/
さらに、Event GridのクライアントライブラリでCloudEventsを扱えるようになった。
Introducing the new Azure Event Grid Client Libraries with CloudEvents v1.0 Support
https://devblogs.microsoft.com/azure-sdk/event-grid-client-libraries/
ということで、例によってJavaでどんな感じになるのか試してみた、と書こうとしたら、すでにGitHubに記載があるので、追記すべきものがなかった…。
Azure Event Grid client library for Java
https://github.com/Azure/azure-sdk-for-java/blob/master/sdk/eventgrid/azure-messaging-eventgrid/README.md
そのため、はまりどころなどをメモとして残しておく。
依存関係
古いドキュメント、例えば以下のドキュメントを見ていると、
Java 用 Azure Event Grid ライブラリ / Azure Event Grid libraries for Java
https://docs.microsoft.com/java/api/overview/azure/eventgrid
以下の依存関係を指定するよう指示がある。
<!-- Old and wrong -->
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure-eventgrid</artifactId>
<version>1.4.0-beta.1</version>
</dependency>
しかしながらCloudEventsを扱う場合には、README.mdにある依存関係を指定する必要がある。
<!-- Correct -->
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-messaging-eventgrid</artifactId>
<version>2.0.0-beta.3</version>
</dependency>
クライアントの作成
同期クライアント、非同期クライアントのいずれも作成できる。まずは同期クライアント。sendCloudEvents()で送信。
// Create Sync Client
EventGridPublisherClient eventGridPublisherClient = new EventGridPublisherClientBuilder()
.credential(new AzureKeyCredential(ACCESS_KEY))
.endpoint(ENDPOINT_URL)
.buildClient();
List<CloudEvent> eventList = new ArrayList<>();
...
eventList.add(new CloudEvent("com/example/source", "Com.Example.ExampleEventType")
.setData("Example Data")
.setTime(OffsetDateTime.now()));
...
// Sent events synchronously
eventGridPublisherClient.sendCloudEvents(eventList);
非同期クライアントは例によってReactorベース。こちらは送信後のレスポンスをとるメソッドとレスポンスをとらないメソッドがある。レスポンスをとるメソッドの場合、Reactorのお作法に則って取得する。
// Create Async Client
EventGridPublisherAsyncClient eventGridPublisherAsyncClient = new EventGridPublisherClientBuilder()
.credential(new AzureKeyCredential(ACCESS_KEY))
.endpoint(ENDPOINT_URL)
.buildAsyncClient();
List<CloudEvent> eventList = new ArrayList<>();
...
eventList.add(new CloudEvent("com/example/source", "Com.Example.ExampleEventType")
.setData("Example Data")
.setTime(OffsetDateTime.now()));
...
// Sent events asynchronously
eventGridPublisherAsyncClient.sendCloudEvents(eventList);
// Able to get response
// eventGridPublisherAsyncClient.sendCloudEventsWithResponse(eventList);
WebhookやAzure Functionでイベントをサブスクライブ
Event GridのクライアントSDKにCloudEventsの取り扱いが入ったとはいえ、Azure FunctionのEvent GridバインディングはまだCloudEventsに対応していないので、Functionsでやるなら前回の記述の通りHTTPバインディングを使うしかない。
Webhookでイベントをサブスクライブする場合は、FunctionではなくApp Serviceを使うことになろう。この場合はSDKを使ってイベントを拾うことができる。