选项
首页首页 Skill API开发 azure-messaging-webpubsub-java

azure-messaging-webpubsub-java

microsoft/skills microsoft/skills

使用适用于 Java 的 Azure Web PubSub SDK 构建实时 Web 应用程序,实现基于 WebSocket 的消息传递、实时更新、聊天以及服务器到客户端的推送通知。

...展开全部
0
更新时间 2026-09-15

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.`向特定组发送消息

最佳实践

  1. 使用组:将连接组织到组中以实现定向消息传递
  2. 用户 ID:将连接与用户 ID 关联以实现用户级消息传递
  3. 令牌过期:设置适当的令牌过期时间以确保安全
  4. 角色:通过角色授予最小所需权限
  5. Hub 隔离:为不同的应用程序功能使用单独的 Hub
  6. 连接管理:清理不活跃的连接

触发短语

  • "Web PubSub Java"
  • "WebSocket messaging Azure"
  • "real-time push notifications"
  • "server-sent events"
  • "chat application backend"
  • "live updates broadcasting"
在 GitHub 上查看
---
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

复制 复制
快速设置: 将技能文件夹复制到 .claude/skills/ 目录。Claude 将自动检测并使用该技能。

相关技能

brightdata-cli
更新时间 2026-06-29
humanize
更新时间 2026-07-07
agentwallet
更新时间 2026-07-07
korean-stock-search
更新时间 2026-07-08
OR