azure-messaging-webpubsub-java
microsoft/skills
Azure Web PubSub SDK for Java を使用してリアルタイムの Web アプリケーションを構築し、WebSocket ベースのメッセージング、ライブ更新、チャット、サーバーからクライアントへのプッシュ通知を有効にします。
...すべて拡張しますJava用Azure Web PubSub SDK
Java用Azure Web PubSub SDKを使用して、リアルタイムの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("<接続文字列>")
.hub("チャット")
.buildClient();
</接続文字列>アクセスキーを使用する場合
import com.azure.core.credential.AzureKeyCredential;
WebPubSubServiceClient client = new WebPubSubServiceClientBuilder()
.credential(new AzureKeyCredential("<アクセスキー>"))
.endpoint("<エンドポイント>")
.hub("チャット")
.buildClient();
</エンドポイント></アクセスキー>DefaultAzureCredentialを使用する場合
import com.azure.core.credential.TokenCredential;
import com.azure.identity.AzureIdentityEnvVars;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.ManagedIdentityCredentialBuilder;
// ローカル開発: DefaultAzureCredential。本番環境: AZURE_TOKEN_CREDENTIALS=prod または AZURE_TOKEN_CREDENTIALS=<特定の資格情報> を設定
TokenCredential credential = new DefaultAzureCredentialBuilder()
.requireEnvVars(AzureIdentityEnvVars.AZURE_TOKEN_CREDENTIALS)
.build();
// または、本番環境で特定の資格情報を直接使用:
// 詳細は https://learn.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable#credential-classes を参照
// TokenCredential credential = new ManagedIdentityCredentialBuilder().build();
WebPubSubServiceClient client = new WebPubSubServiceClientBuilder()
.credential(credential)
.endpoint("<エンドポイント>")
.hub("チャット")
.buildClient();
</エンドポイント></特定の資格情報>非同期クライアント
import com.azure.messaging.webpubsub.WebPubSubServiceAsyncClient;
WebPubSubServiceAsyncClient asyncClient = new WebPubSubServiceClientBuilder()
.connectionString("<接続文字列>")
.hub("チャット")
.buildAsyncClient();
</接続文字列>主要な概念
- ハブ: 接続の論理的な分離単位
- グループ: ハブ内の接続のサブセット
- 接続: 個別のWebSocketクライアント接続
- ユーザー: 複数の接続を持つことができるエンティティ
コアパターン
すべての接続への送信
import com.azure.messaging.webpubsub.models.WebPubSubContentType;
// テキストメッセージの送信
client.sendToAll("皆さん、こんにちは!", WebPubSubContentType.TEXT_PLAIN);
// JSONの送信
String jsonMessage = "{\"type\": \"通知\", \"message\": \"新しいアップデート!\"}";
client.sendToAll(jsonMessage, WebPubSubContentType.APPLICATION_JSON);
フィルター付きのすべての接続への送信
import com.azure.core.http.rest.RequestOptions;
import com.azure.core.util.BinaryData;
BinaryData message = BinaryData.fromString("フィルター対象のユーザーへこんにちは!");
// userIdでフィルタリング
client.sendToAllWithResponse(
message,
WebPubSubContentType.TEXT_PLAIN,
message.getLength(),
new RequestOptions().addQueryParam("filter", "userId ne 'user1'"));
// グループでフィルタリング
client.sendToAllWithResponse(
message,
WebPubSubContentType.TEXT_PLAIN,
message.getLength(),
new RequestOptions().addQueryParam("filter", "'GroupA' in groups and not('GroupB' in groups)"));
グループへの送信
// グループ内のすべての接続に送信
client.sendToGroup("java開発者", "こんにちはJava開発者!", WebPubSubContentType.TEXT_PLAIN);
// グループにJSONを送信
String json = "{\"event\": \"更新\", \"data\": {\"version\": \"2.0\"}}";
client.sendToGroup("購読者", json, WebPubSubContentType.APPLICATION_JSON);
特定の接続への送信
// IDで特定の接続に送信
client.sendToConnection("connectionId123", "プライベートメッセージ", WebPubSubContentType.TEXT_PLAIN);
ユーザーへの送信
// 特定のユーザーのすべての接続に送信
client.sendToUser("andy", "こんにちはAndy!", WebPubSubContentType.TEXT_PLAIN);
グループの管理
// 接続をグループに追加
client.addConnectionToGroup("プレミアムユーザー", "connectionId123");
// 接続をグループから削除
client.removeConnectionFromGroup("プレミアムユーザー", "connectionId123");
// ユーザーをグループに追加(すべての接続)
client.addUserToGroup("管理者グループ", "userId456");
// ユーザーをグループから削除
client.removeUserFromGroup("管理者グループ", "userId456");
// ユーザーがグループにいるか確認
boolean exists = client.userExistsInGroup("管理者グループ", "userId456");
接続の管理
// 接続が存在するか確認
boolean connected = client.connectionExists("connectionId123");
// 接続を閉じる
client.closeConnection("connectionId123");
// 理由を指定して接続を閉じる
client.closeConnection("connectionId123", "セッションの有効期限切れ");
// ユーザーが存在するか確認(接続を持っているか)
boolean userOnline = client.userExists("userId456");
// ユーザーのすべての接続を閉じる
client.closeUserConnections("userId456");
// グループ内のすべての接続を閉じる
client.closeGroupConnections("非アクティブグループ");
クライアントアクセストークンの生成
import com.azure.messaging.webpubsub.models.GetClientAccessTokenOptions;
import com.azure.messaging.webpubsub.models.WebPubSubClientAccessToken;
// 基本トークン
WebPubSubClientAccessToken token = client.getClientAccessToken(
new GetClientAccessTokenOptions());
System.out.println("URL: " + token.getUrl());
// ユーザーID付き
WebPubSubClientAccessToken userToken = client.getClientAccessToken(
new GetClientAccessTokenOptions().setUserId("user123"));
// ロール(権限)付き
WebPubSubClientAccessToken roleToken = client.getClientAccessToken(
new GetClientAccessTokenOptions()
.setUserId("user123")
.addRole("webpubsub.joinLeaveGroup")
.addRole("webpubsub.sendToGroup"));
// 接続時に参加するグループ付き
WebPubSubClientAccessToken groupToken = client.getClientAccessToken(
new GetClientAccessTokenOptions()
.setUserId("user123")
.addGroup("お知らせ")
.addGroup("更新"));
// カスタム有効期限付き
WebPubSubClientAccessToken expToken = client.getClientAccessToken(
new GetClientAccessTokenOptions()
.setUserId("user123")
.setExpiresAfter(Duration.ofHours(2)));
権限の付与/取り消し
import com.azure.messaging.webpubsub.models.WebPubSubPermission;
// グループへの送信権限を付与
client.grantPermission(
WebPubSubPermission.SEND_TO_GROUP,
"connectionId123",
new RequestOptions().addQueryParam("targetName", "チャットルーム"));
// 権限を取り消す
client.revokePermission(
WebPubSubPermission.SEND_TO_GROUP,
"connectionId123",
new RequestOptions().addQueryParam("targetName", "チャットルーム"));
// 権限を確認
boolean hasPermission = client.checkPermission(
WebPubSubPermission.SEND_TO_GROUP,
"connectionId123",
new RequestOptions().addQueryParam("targetName", "チャットルーム"));
非同期操作
asyncClient.sendToAll("非同期メッセージ!", WebPubSubContentType.TEXT_PLAIN)
.subscribe(
unused -> System.out.println("メッセージ送信完了"),
error -> System.err.println("エラー: " + error.getMessage())
);
asyncClient.sendToGroup("開発者", "グループメッセージ", WebPubSubContentType.TEXT_PLAIN)
.doOnSuccess(v -> System.out.println("グループに送信完了"))
.doOnError(e -> System.err.println("失敗: " + e))
.subscribe();
エラー処理
import com.azure.core.exception.HttpResponseException;
try {
client.sendToConnection("無効なID", "テスト", WebPubSubContentType.TEXT_PLAIN);
} catch (HttpResponseException e) {
System.out.println("ステータス: " + e.getResponse().getStatusCode());
System.out.println("エラー: " + e.getMessage());
}
環境変数
WEB_PUBSUB_CONNECTION_STRING=Endpoint=https://<リソース>.webpubsub.azure.com;AccessKey=... # Entra ID認証の代替
WEB_PUBSUB_ENDPOINT=https://<リソース>.webpubsub.azure.com # AzureKeyCredentialまたはTokenCredential認証に必要
WEB_PUBSUB_ACCESS_KEY=<あなたのアクセスキー> # AzureKeyCredential認証の場合のみ必要
AZURE_TOKEN_CREDENTIALS=prod # 本番環境でDefaultAzureCredentialを使用する場合のみ必要
</あなたのアクセスキー></リソース></リソース>クライアントのロール
| ロール | 権限 |
|---|---|
| `webpubsub.joinLeaveGroup` | 任意のグループに参加/退出 |
| `webpubsub.sendToGroup` | 任意のグループに送信 |
| `webpubsub.joinLeaveGroup.` | 特定のグループに参加/退出 |
| `webpubsub.sendToGroup.` | 特定のグループに送信 |
ベストプラクティス
- グループの使用: ターゲットメッセージングのために接続をグループに整理する
- ユーザーID: ユーザーレベルのメッセージングのために接続をユーザーIDに関連付ける
- トークンの有効期限: セキュリティのために適切なトークン有効期限を設定する
- ロール: 必要な最小限の権限をロールを通じて付与する
- ハブの分離: 異なるアプリケーション機能に別のハブを使用する
- 接続管理: 非アクティブな接続をクリーンアップする
トリガーフレーズ
- "Web PubSub Java"
- "WebSocketメッセージング Azure"
- "リアルタイムプッシュ通知"
- "サーバー送信イベント"
- "チャットアプリケーションバックエンド"
- "ライブアップデートブロードキャスト"
---
name: azure-messaging-webpubsub-java
description: Build real-time web applications with Azure Web PubSub SDK for Java, enabling WebSocket-based messaging, live updates, chat, and server-to-client push notifications.
license: MIT
---
# Azure Web PubSub SDK for Java
Build real-time web applications using the Azure Web PubSub SDK for Java.
## Installation
```xml
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-messaging-webpubsub</artifactId>
<version>1.5.0</version>
</dependency>
```
## Client Creation
### With Connection String
```java
import com.azure.messaging.webpubsub.WebPubSubServiceClient;
import com.azure.messaging.webpubsub.WebPubSubServiceClientBuilder;
WebPubSubServiceClient client = new WebPubSubServiceClientBuilder()
.connectionString("<connection-string>")
.hub("chat")
.buildClient();
```
### With Access Key
```java
import com.azure.core.credential.AzureKeyCredential;
WebPubSubServiceClient client = new WebPubSubServiceClientBuilder()
.credential(new AzureKeyCredential("<access-key>"))
.endpoint("<endpoint>")
.hub("chat")
.buildClient();
```
### With DefaultAzureCredential
```java
import com.azure.core.credential.TokenCredential;
import com.azure.identity.AzureIdentityEnvVars;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.ManagedIdentityCredentialBuilder;
// Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>
TokenCredential credential = new DefaultAzureCredentialBuilder()
.requireEnvVars(AzureIdentityEnvVars.AZURE_TOKEN_CREDENTIALS)
.build();
// Or use a specific credential directly in production:
// See https://learn.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable#credential-classes
// TokenCredential credential = new ManagedIdentityCredentialBuilder().build();
WebPubSubServiceClient client = new WebPubSubServiceClientBuilder()
.credential(credential)
.endpoint("<endpoint>")
.hub("chat")
.buildClient();
```
### Async Client
```java
import com.azure.messaging.webpubsub.WebPubSubServiceAsyncClient;
WebPubSubServiceAsyncClient asyncClient = new WebPubSubServiceClientBuilder()
.connectionString("<connection-string>")
.hub("chat")
.buildAsyncClient();
```
## Key Concepts
- **Hub**: Logical isolation unit for connections
- **Group**: Subset of connections within a hub
- **Connection**: Individual WebSocket client connection
- **User**: Entity that can have multiple connections
## Core Patterns
### Send to All Connections
```java
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);
```
### Send to All with Filter
```java
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 Group
```java
// 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 Specific Connection
```java
// Send to a specific connection by ID
client.sendToConnection("connectionId123", "Private message", WebPubSubContentType.TEXT_PLAIN);
```
### Send to User
```java
// Send to all connections for a specific user
client.sendToUser("andy", "Hello Andy!", WebPubSubContentType.TEXT_PLAIN);
```
### Manage Groups
```java
// 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");
```
### Manage Connections
```java
// 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");
```
### Generate Client Access Token
```java
import com.azure.messaging.webpubsub.models.GetClientAccessTokenOptions;
import com.azure.messaging.webpubsub.models.WebPubSubClientAccessToken;
// Basic token
WebPubSubClientAccessToken token = client.getClientAccessToken(
new GetClientAccessTokenOptions());
System.out.println("URL: " + token.getUrl());
// 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)));
```
### Grant/Revoke Permissions
```java
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"));
```
### Async Operations
```java
asyncClient.sendToAll("Async message!", WebPubSubContentType.TEXT_PLAIN)
.subscribe(
unused -> System.out.println("Message sent"),
error -> System.err.println("Error: " + error.getMessage())
);
asyncClient.sendToGroup("developers", "Group message", WebPubSubContentType.TEXT_PLAIN)
.doOnSuccess(v -> System.out.println("Sent to group"))
.doOnError(e -> System.err.println("Failed: " + e))
.subscribe();
```
## Error Handling
```java
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());
}
```
## Environment Variables
```bash
WEB_PUBSUB_CONNECTION_STRING=Endpoint=https://<resource>.webpubsub.azure.com;AccessKey=... # Alternative to Entra ID auth
WEB_PUBSUB_ENDPOINT=https://<resource>.webpubsub.azure.com # Required for AzureKeyCredential or TokenCredential auth
WEB_PUBSUB_ACCESS_KEY=<your-access-key> # Only required for AzureKeyCredential auth
AZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in production
```
## Client Roles
| Role | Permission |
|------|------------|
| `webpubsub.joinLeaveGroup` | Join/leave any group |
| `webpubsub.sendToGroup` | Send to any group |
| `webpubsub.joinLeaveGroup.<group>` | Join/leave specific group |
| `webpubsub.sendToGroup.<group>` | Send to specific group |
## Best Practices
1. **Use Groups**: Organize connections into groups for targeted messaging
2. **User IDs**: Associate connections with user IDs for user-level messaging
3. **Token Expiration**: Set appropriate token expiration for security
4. **Roles**: Grant minimal required permissions via roles
5. **Hub Isolation**: Use separate hubs for different application features
6. **Connection Management**: Clean up inactive connections
## Trigger Phrases
- "Web PubSub Java"
- "WebSocket messaging Azure"
- "real-time push notifications"
- "server-sent events"
- "chat application backend"
- "live updates broadcasting"
すべてのファイル
0件のファイルazure-messaging-webpubsub-javaをインストール
スキルファイルをダウンロードして .claude/skills/ ディレクトリに展開してください。
ZIPをダウンロードリポジトリをクローンし、スキルファイルをプロジェクトにコピーしてください。
git clone https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-java/skills/azure-messaging-webpubsub-java # Copy SKILL.md to your .claude/skills/ directory
コピー





家
