
关于
使用 Azure Web PubSub Java SDK 构建实时 Web 应用。用于实现基于 WebSocket 的消息传递、实时通知和协作功能。
name: azure-messaging-webpubsub-java description: "使用 Azure Web PubSub SDK for Java 构建实时 Web 应用。适用于实现基于 WebSocket 的消息传递、实时更新、聊天应用或服务器到客户端的推送通知。" risk: unknown source: community date_added: "2026-02-27"
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();
核心概念
- Hub(中心):连接的逻辑隔离单元
- Group(组):Hub 内的连接子集
- Connection(连接):单个 WebSocket 客户端连接
- User(用户):可拥有多个连接的实体
核心模式
发送给所有连接
import com.azure.messaging.webpubsub.models.WebPubSubContentType;
// 发送文本消息
client.sendToAll("Hello everyone!", WebPubSubContentType.TEXT_PLAIN);
// 发送 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!");
// 按 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", "Hello Java devs!", WebPubSubContentType.TEXT_PLAIN);
// 发送 JSON 给组
String json = "{\"event\": \"update\", \"data\": {\"version\": \"2.0\"}}";
client.sendToGroup("subscribers", json, WebPubSubContentType.APPLICATION_JSON);
发送给特定连接
// 通过连接 ID 发送给特定连接
client.sendToConnection("connectionId123", "Private message", WebPubSubContentType.TEXT_PLAIN);
发送给用户
// 发送给特定用户的所有连接
client.sendToUser("andy", "Hello 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", "Session expired");
// 检查用户是否存在(是否有任何连接)
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(
兼容工具
Claude CodeCursor
标签
后端开发
