azure-messaging-webpubsub-java
microsoft/skills
Создавайте веб-приложения в реальном времени с помощью Azure Web PubSub SDK для Java, обеспечивая обмен сообщениями на основе WebSocket, обновления в реальном времени, чат и серверные push-уведомления для клиентов.
...Расширить всеSDK для Java Azure Web PubSub
Создавайте веб-приложения реального времени с использованием SDK для Java Azure Web PubSub.
Установка
<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();
</connection-string>С помощью ключа доступа
import com.azure.core.credential.AzureKeyCredential;
WebPubSubServiceClient client = new WebPubSubServiceClientBuilder()
.credential(new AzureKeyCredential("<access-key>"))
.endpoint("<endpoint>")
.hub("chat")
.buildClient();
</endpoint></access-key>С помощью 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=<specific_credential>
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("<endpoint>")
.hub("chat")
.buildClient();
</endpoint></specific_credential>Асинхронный клиент
import com.azure.messaging.webpubsub.WebPubSubServiceAsyncClient;
WebPubSubServiceAsyncClient asyncClient = new WebPubSubServiceClientBuilder()
.connectionString("<connection-string>")
.hub("chat")
.buildAsyncClient();
</connection-string>Ключевые концепции
- Hub (Центр): Логическая единица изоляции для соединений
- Группа: Подмножество соединений в пределах центра
- Соединение: Индивидуальное соединение клиента WebSocket
- Пользователь: Сущность, которая может иметь несколько соединений
Основные шаблоны
Отправка всем соединениям
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", "Привет, Энди!", 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());
// С идентификатором пользователя
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", "test", WebPubSubContentType.TEXT_PLAIN);
} catch (HttpResponseException e) {
System.out.println("Статус: " + e.getResponse().getStatusCode());
System.out.println("Ошибка: " + e.getMessage());
}
Переменные среды
WEB_PUBSUB_CONNECTION_STRING=Endpoint=https://<resource>.webpubsub.azure.com;AccessKey=... # Альтернатива аутентификации Entra ID
WEB_PUBSUB_ENDPOINT=https://<resource>.webpubsub.azure.com # Требуется для аутентификации AzureKeyCredential или TokenCredential
WEB_PUBSUB_ACCESS_KEY=<your-access-key> # Требуется только для аутентификации AzureKeyCredential
AZURE_TOKEN_CREDENTIALS=prod # Требуется только если DefaultAzureCredential используется в продуктиве
</your-access-key></resource></resource>Роли клиента
| Роль | Разрешение |
|---|---|
| `webpubsub.joinLeaveGroup` | Присоединение/выход из любой группы |
| `webpubsub.sendToGroup` | Отправка в любую группу |
| `webpubsub.joinLeaveGroup. | Присоединение/выход из конкретной группы |
| `webpubsub.sendToGroup. | Отправка в конкретную группу |
Рекомендации
- Используйте группы: Организуйте соединения в группы для целевой рассылки
- Идентификаторы пользователей: Связывайте соединения с идентификаторами пользователей для рассылки на уровне пользователя
- Истечение токена: Устанавливайте соответствующее время истечения токена для безопасности
- Роли: Предоставляйте минимально необходимые разрешения через роли
- Изоляция центров: Используйте отдельные центры для различных функций приложения
- Управление соединениями: Очищайте неактивные соединения
Триггерные фразы
- "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
Копировать





Дом
