azure-messaging-webpubsub-java について
Azure Web PubSub を使ったリアルタイムアプリ開発向けの Java SDK スキルです。同期・非同期クライアント、メッセージ配信、グループや接続の管理、アクセス制御を扱います。
主な機能
- 01同期・非同期クライアントの作成
- 02グループ・ユーザー・接続へのメッセージ送信
- 03グループと接続の管理
- 04クライアントアクセストークンの生成
- 05権限の付与と取り消し
活用シーン
- 01グループメッセージ対応のチャットバックエンド構築
- 02リアルタイム通知の配信
- 03WebSocket クライアントアクセスの管理
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ sickn33/ agentic-awesome-skills --skill azure-messaging-webpubsub-javaインストール後、Claude Code で/azure-messaging-webpubsub-javaを入力して読み込まれたか確認します。
詳細
Azure Web PubSub SDK for Java
Azure Web PubSub SDK for Java を使用して、リアルタイムの Web アプリケーションを構築します。
インストール
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-messaging-webpubsub</artifactId>
<version>1.5.0</version>
</dependency>
クライアントの作成
接続文字列を使用する場合
import com.azure.messaging.webpubsub.WebPubSubServiceClient;
import com.azure.messaging.webpubsub.WebPubSubServiceClientBuilder;
WebPubSubServiceClient client = new WebPubSubServiceClientBuilder()
.connectionString("<connection-string>")
.hub("chat")
.buildClient();
アクセスキーを使用する場合
import com.azure.core.credential.AzureKeyCredential;
WebPubSubServiceClient client = new WebPubSubServiceClientBuilder()
.credential(new AzureKeyCredential("<access-key>"))
.endpoint("<endpoint>")
.hub("chat")
.buildClient();
DefaultAzureCredential を使用する場合
import com.azure.identity.DefaultAzureCredentialBuilder;
WebPubSubServiceClient client = new WebPubSubServiceClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.endpoint("<endpoint>")
.hub("chat")
.buildClient();
非同期クライアント
import com.azure.messaging.webpubsub.WebPubSubServiceAsyncClient;
WebPubSubServiceAsyncClient asyncClient = new WebPubSubServiceClientBuilder()
.connectionString("<connection-string>")
.hub("chat")
.buildAsyncClient();
主な概念
- ハブ:接続を論理的に分離する単位
- グループ:ハブ内の接続のサブセット
- 接続:個別の WebSocket クライアント接続
- ユーザー:複数の接続を持つことができるエンティティ
認可と配信の境界
クライアントトークンは認証済みのサーバーからのみ発行し、ユーザー/グループ/テナントの ID はリクエストパラメーターではなく、信頼できるアカウント状態から取得してください。グループスコープのロールと短い有効期限を優先してください。制限のない参加/送信ロールでは、ハブ内の任意のグループにアクセスできます。ベアラー URL や接続シークレットをログに記録しないでください。ブロードキャスト/グループ変更/切断には、承認済みの対象範囲が必要です。サービスが受け付けたからといって、すべてのクライアントがメッセージを受信/処理したことにはなりません。コード例は記載された SDK バージョンを対象としており、完全な認証/再試行のアプリケーションロジックは省略しています。
基本的なパターン
すべての接続に送信する
import com.azure.messaging.webpubsub.models.WebPubSubContentType;
// Send text message
client.sendToAll("Hello everyone!", WebPubSubContentType.TEXT_PLAIN);
// Send JSON
String jsonMessage = "{\"type\": \"notification\", \"message\": \"New update!\"}";
client.sendToAll(jsonMessage, WebPubSubContentType.APPLICATION_JSON);
フィルターを使用してすべてに送信する
import com.azure.core.http.rest.RequestOptions;
import com.azure.core.util.BinaryData;
BinaryData message = BinaryData.fromString("Hello filtered users!");
// Filter by userId
client.sendToAllWithResponse(
message,
WebPubSubContentType.TEXT_PLAIN,
message.getLength(),
new RequestOptions().addQueryParam("filter", "userId ne 'user1'"));
// Filter by groups
client.sendToAllWithResponse(
message,
WebPubSubContentType.TEXT_PLAIN,
message.getLength(),
new RequestOptions().addQueryParam("filter", "'GroupA' in groups and not('GroupB' in groups)"));
グループに送信する
// Send to all connections in a group
client.sendToGroup("java-developers", "Hello Java devs!", WebPubSubContentType.TEXT_PLAIN);
// Send JSON to group
String json = "{\"event\": \"update\", \"data\": {\"version\": \"2.0\"}}";
client.sendToGroup("subscribers", json, WebPubSubContentType.APPLICATION_JSON);
特定の接続に送信する
// Send to a specific connection by ID
client.sendToConnection("connectionId123", "Private message", WebPubSubContentType.TEXT_PLAIN);
ユーザーに送信する
// Send to all connections for a specific user
client.sendToUser("andy", "Hello Andy!", WebPubSubContentType.TEXT_PLAIN);
グループを管理する
// Add connection to group
client.addConnectionToGroup("premium-users", "connectionId123");
// Remove connection from group
client.removeConnectionFromGroup("premium-users", "connectionId123");
// Add user to group (all their connections)
client.addUserToGroup("admin-group", "userId456");
// Remove user from group
client.removeUserFromGroup("admin-group", "userId456");
// Check if user is in group
boolean exists = client.userExistsInGroup("admin-group", "userId456");
接続を管理する
// Check if connection exists
boolean connected = client.connectionExists("connectionId123");
// Close a connection
client.closeConnection("connectionId123");
// Close with reason
client.closeConnection("connectionId123", "Session expired");
// Check if user exists (has any connections)
boolean userOnline = client.userExists("userId456");
// Close all connections for a user
client.closeUserConnections("userId456");
// Close all connections in a group
client.closeGroupConnections("inactive-group");
クライアントアクセストークンを生成する
import com.azure.messaging.webpubsub.models.GetClientAccessTokenOptions;
import com.azure.messaging.webpubsub.models.WebPubSubClientAccessToken;
// Basic token
WebPubSubClientAccessToken token = client.getClientAccessToken(
new GetClientAccessTokenOptions());
// Return token.getUrl() only to the authenticated authorized client over TLS; never log it.
// With user ID
WebPubSubClientAccessToken userToken = client.getClientAccessToken(
new GetClientAccessTokenOptions().setUserId("user123"));
// With roles (permissions)
WebPubSubClientAccessToken roleToken = client.getClientAccessToken(
new GetClientAccessTokenOptions()
.setUserId("user123")
.addRole("webpubsub.joinLeaveGroup")
.addRole("webpubsub.sendToGroup"));
// With groups to join on connect
WebPubSubClientAccessToken groupToken = client.getClientAccessToken(
new GetClientAccessTokenOptions()
.setUserId("user123")
.addGroup("announcements")
.addGroup("updates"));
// With custom expiration
WebPubSubClientAccessToken expToken = client.getClientAccessToken(
new GetClientAccessTokenOptions()
.setUserId("user123")
.setExpiresAfter(Duration.ofHours(2)));
権限を付与/取り消す
import com.azure.messaging.webpubsub.models.WebPubSubPermission;
// Grant permission to send to a group
client.grantPermission(
WebPubSubPermission.SEND_TO_GROUP,
"connectionId123",
new RequestOptions().addQueryParam("targetName", "chat-room"));
// Revoke permission
client.revokePermission(
WebPubSubPermission.SEND_TO_GROUP,
"connectionId123",
new RequestOptions().addQueryParam("targetName", "chat-room"));
// Check permission
boolean hasPermission = client.checkPermission(
WebPubSubPermission.SEND_TO_GROUP,
"connectionId123",
new RequestOptions().addQueryParam("targetName", "chat-room"));
非同期操作
asyncClient.sendToAll("Async message!", WebPubSubContentType.TEXT_PLAIN)
.subscribe(
unused -> { },
error -> System.err.println("Error: " + error.getMessage()),
() -> System.out.println("Message accepted by service")
);
asyncClient.sendToGroup("developers", "Group message", WebPubSubContentType.TEXT_PLAIN)
.doOnSuccess(v -> System.out.println("Sent to group"))
.doOnError(e -> System.err.println("Failed: " + e))
.subscribe();
エラー処理
import com.azure.core.exception.HttpResponseException;
try {
client.sendToConnection("invalid-id", "test", WebPubSubContentType.TEXT_PLAIN);
} catch (HttpResponseException e) {
System.out.println("Status: " + e.getResponse().getStatusCode());
System.out.println("Error: " + e.getMessage());
}
環境変数
WEB_PUBSUB_CONNECTION_STRING=Endpoint=https://<resource>.webpubsub.azure.com;AccessKey=...
WEB_PUBSUB_ENDPOINT=https://<resource>.webpubsub.azure.com
WEB_PUBSUB_ACCESS_KEY=<your-access-key>
クライアントロール
| ロール | 権限 |
|---|---|
webpubsub.joinLeaveGroup | 任意のグループへの参加/退出 |
webpubsub.sendToGroup | 任意のグループへの送信 |
webpubsub.joinLeaveGroup.<group> | 特定のグループへの参加/退出 |
webpubsub.sendToGroup.<group> | 特定のグループへの送信 |
ベストプラクティス
- グループを使用する:接続をグループに整理して、対象を絞ったメッセージを送信します
- ユーザー ID:ユーザーレベルのメッセージングを行うため、接続をユーザー ID に関連付けます
- トークンの有効期限:セキュリティのため、適切なトークンの有効期限を設定します
- ロール:ロールを通じて、必要最小限の権限を付与します
- ハブの分離:アプリケーションの機能ごとに別々のハブを使用します
- 接続管理:非アクティブな接続をクリーンアップします
トリガーフレーズ
- 「Web PubSub Java」
- 「Azure WebSocket メッセージング」
- 「リアルタイムのプッシュ通知」
- 「サーバー送信イベント」
- 「チャットアプリケーションのバックエンド」
- 「ライブ更新のブロードキャスト」
使用する場合
このスキルは、概要で説明されているワークフローまたはアクションを実行する場合に適用できます。
制限事項
- このスキルは、タスクが上記の説明範囲に明確に一致する場合にのみ使用してください。
- 出力を、環境固有の検証、テスト、または専門家によるレビューの代わりとして扱わないでください。
- 必要な入力、権限、安全上の境界、または成功基準が不足している場合は、停止して確認を求めてください。
コメント
Markdown 対応