azure-messaging-webpubsub-java
microsoft/skills
使用適用於 Java 的 Azure Web PubSub SDK 構建實時 Web 應用程式,實現基於 WebSocket 的訊息傳遞、實時更新、聊天以及伺服器到客戶端的推送通知。
...展開全部Azure Web PubSub Java SDK
使用 Azure Web PubSub Java 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("chat")
.buildClient();
</連線字串>使用訪問金鑰
import com.azure.core.credential.AzureKeyCredential;
WebPubSubServiceClient client = new WebPubSubServiceClientBuilder()
.credential(new AzureKeyCredential("<訪問金鑰>"))
.endpoint("<端點>")
.hub("chat")
.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("chat")
.buildClient();
</端點></特定憑據>非同步客戶端
import com.azure.messaging.webpubsub.WebPubSubServiceAsyncClient;
WebPubSubServiceAsyncClient asyncClient = new WebPubSubServiceClientBuilder()
.connectionString("<連線字串>")
.hub("chat")
.buildAsyncClient();
</連線字串>核心概念
- Hub(中心):連線的邏輯隔離單元
- Group(組):Hub 內連線的子集
- Connection(連線):單個 WebSocket 客戶端連線
- User(使用者):可以擁有多個連線的實體
核心模式
向所有連線傳送訊息
import com.azure.messaging.webpubsub.models.WebPubSubContentType;
// 傳送文字訊息
client.sendToAll("大家好!", WebPubSubContentType.TEXT_PLAIN);
// 傳送 JSON
String jsonMessage = "{\"type\": \"notification\", \"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-developers", "你好 Java 開發者!", WebPubSubContentType.TEXT_PLAIN);
// 向組傳送 JSON
String json = "{\"event\": \"update\", \"data\": {\"version\": \"2.0\"}}";
client.sendToGroup("subscribers", json, WebPubSubContentType.APPLICATION_JSON);
向特定連線傳送訊息
// 按 ID 向特定連線傳送訊息
client.sendToConnection("connectionId123", "私密訊息", WebPubSubContentType.TEXT_PLAIN);
向使用者傳送訊息
// 向特定使用者的所有連線傳送訊息
client.sendToUser("andy", "你好 Andy!", WebPubSubContentType.TEXT_PLAIN);
管理組
// 將連線新增到組
client.addConnectionToGroup("premium-users", "connectionId123");
// 從組中移除連線
client.removeConnectionFromGroup("premium-users", "connectionId123");
// 將使用者新增到組(其所有連線)
client.addUserToGroup("admin-group", "userId456");
// 從組中移除使用者
client.removeUserFromGroup("admin-group", "userId456");
// 檢查使用者是否在組中
boolean exists = client.userExistsInGroup("admin-group", "userId456");
管理連線
// 檢查連線是否存在
boolean connected = client.connectionExists("connectionId123");
// 關閉連線
client.closeConnection("connectionId123");
// 帶原因關閉連線
client.closeConnection("connectionId123", "會話已過期");
// 檢查使用者是否存在(擁有任何連線)
boolean userOnline = client.userExists("userId456");
// 關閉使用者的所有連線
client.closeUserConnections("userId456");
// 關閉組中的所有連線
client.closeGroupConnections("inactive-group");
生成客戶端訪問令牌
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("announcements")
.addGroup("updates"));
// 帶自定義過期時間
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", "chat-room"));
// 撤銷許可權
client.revokePermission(
WebPubSubPermission.SEND_TO_GROUP,
"connectionId123",
new RequestOptions().addQueryParam("targetName", "chat-room"));
// 檢查許可權
boolean hasPermission = client.checkPermission(
WebPubSubPermission.SEND_TO_GROUP,
"connectionId123",
new RequestOptions().addQueryParam("targetName", "chat-room"));
非同步操作
asyncClient.sendToAll("非同步訊息!", WebPubSubContentType.TEXT_PLAIN)
.subscribe(
unused -> System.out.println("訊息已傳送"),
error -> System.err.println("錯誤: " + error.getMessage())
);
asyncClient.sendToGroup("developers", "組訊息", WebPubSubContentType.TEXT_PLAIN)
.doOnSuccess(v -> System.out.println("已傳送到組"))
.doOnError(e -> System.err.println("失敗: " + e))
.subscribe();
錯誤處理
import com.azure.core.exception.HttpResponseException;
try {
client.sendToConnection("invalid-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 關聯以實現使用者級訊息傳遞
- 令牌過期:設定適當的令牌過期時間以確保安全
- 角色:透過角色授予最小所需許可權
- Hub 隔離:為不同的應用程式功能使用單獨的 Hub
- 連線管理:清理不活躍的連線
觸發短語
- "Web PubSub Java"
- "WebSocket messaging Azure"
- "real-time push notifications"
- "server-sent events"
- "chat application backend"
- "live updates broadcasting"
---
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
複製





首頁
