azure-messaging-webpubsub-java – skill Lập trình cho agent AI
Xây dựng ứng dụng web thời gian thực với Azure Web PubSub SDK cho Java. Dùng khi triển khai nhắn tin dựa trên WebSocket, cập nhật trực tiếp, ứng dụng chat hoặc push thông báo từ server tới client.
Cài skill azure-messaging-webpubsub-java bằng một lệnh
Chọn công cụ bạn đang dùng, copy lệnh và dán vào terminal. Skill sẽ nằm trong thư mục skills của công cụ đó và sẵn sàng dùng ở phiên làm việc tiếp theo.
Claude Code
mkdir -p ~/.claude/skills && curl -fsSL https://skill.dn1nguoi.com/z/azure-messaging-webpubsub-java-ee164.tgz | tar xz -C ~/.claude/skills
Gọi trong Claude Code: /azure-messaging-webpubsub-java – rồi mô tả công việc bạn muốn làm.
Codex
mkdir -p ~/.codex/skills && curl -fsSL https://skill.dn1nguoi.com/z/azure-messaging-webpubsub-java-ee164.tgz | tar xz -C ~/.codex/skills
Gọi trong Codex: $azure-messaging-webpubsub-java – rồi mô tả công việc bạn muốn làm.
Hermes Agent
mkdir -p ~/.hermes/skills && curl -fsSL https://skill.dn1nguoi.com/z/azure-messaging-webpubsub-java-ee164.tgz | tar xz -C ~/.hermes/skills
Gọi trong Hermes Agent: /azure-messaging-webpubsub-java – rồi mô tả công việc bạn muốn làm.
DeepSeek
mkdir -p ~/.deepcode/skills && curl -fsSL https://skill.dn1nguoi.com/z/azure-messaging-webpubsub-java-ee164.tgz | tar xz -C ~/.deepcode/skills
Gọi trong DeepSeek: /azure-messaging-webpubsub-java – rồi mô tả công việc bạn muốn làm.
Nội dung SKILL.md
Nội dung SKILL.md gốc bằng tiếng Anh.
Azure Web PubSub SDK for Java
Build real-time web applications using the Azure Web PubSub SDK for Java.
Installation
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-messaging-webpubsub</artifactId>
<version>1.5.0</version>
</dependency>Client Creation
With Connection String
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
import com.azure.core.credential.AzureKeyCredential;
WebPubSubServiceClient client = new WebPubSubServiceClientBuilder()
.credential(new AzureKeyCredential("<access-key>"))
.endpoint("<endpoint>")
.hub("chat")
.buildClient();With DefaultAzureCredential
import com.azure.identity.DefaultAzureCredentialBuilder;
WebPubSubServiceClient client = new WebPubSubServiceClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.endpoint("<endpoint>")
.hub("chat")
.buildClient();Async Client
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
Authorization and delivery boundaries
Issue client tokens only from an authenticated server; derive user/group/tenant identity from trusted account state, not request parameters. Prefer group-scoped roles and short expirations; unrestricted join/send roles allow access to any group in the hub. Do not log bearer URLs or connection secrets. Broadcasts/group changes/disconnects require approved target scope; service acceptance does not establish every client received/processed a message. The snippets target the stated SDK version and omit complete auth/retry application logic.
Core Patterns
Send to All Connections
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
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
// 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
// Send to a specific connection by ID
client.sendToConnection("connectionId123", "Private message", WebPubSubContentType.TEXT_PLAIN);Send to User
// Send to all connections for a specific user
client.sendToUser("andy", "Hello Andy!", WebPubSubContentType.TEXT_PLAIN);Manage Groups
// 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
// 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
import com.azure.messaging.webpubsub.models.GetClientAccessTokenOptions;
import com.azure.messaging.webpubsub.models.WebPubSubClientAccessToken;
// Basic token
WebPubSubClientAccessToken token = client.getClientAccessToken(
new GetClientAccessTokenOptions());
// Return token.getUrl() only to the authenticated authorized client over TLS; never log it.
// 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
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
asyncClient.sendToAll("Async message!", WebPubSubContentType.TEXT_PLAIN)
.subscribe(
unused -> { },
error -> System.err.println("Error: " + error.getMessage()),
() -> System.out.println("Message accepted by service")
);
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
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
WEB_PUBSUB_CONNECTION_STRING=Endpoint=https://<resource>.webpubsub.azure.com;AccessKey=...
WEB_PUBSUB_ENDPOINT=https://<resource>.webpubsub.azure.com
WEB_PUBSUB_ACCESS_KEY=<your-access-key>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"
When to Use
This skill is applicable to execute the workflow or a
… (nội dung đầy đủ có trong gói tải về)
Skill liên quan
- modern-javascript-patterns – Thành thạo các tính năng ES6+ như async/await, destructuring, spread operator, arrow…
- monorepo-management – Thành thạo quản lý monorepo với Turborepo, Nx và pnpm workspaces để xây dựng kho nhiều…
- cto-advisor – Hướng dẫn lãnh đạo kỹ thuật cho đội ngũ kỹ sư, quyết định kiến trúc và chiến lược công…
- cto-review – /c-level-agents:cto-review [plan] — Rà soát kiến trúc và khả năng mở rộng. Nợ kỹ thuật…
- imessage – Gửi và nhận iMessage/SMS qua CLI imsg trên macOS.
- multi-reviewer-patterns – Điều phối code review song song trên nhiều khía cạnh chất lượng, với khử trùng lặp phát…
- inference-sh-cli – Chạy hơn 150 ứng dụng AI (hình ảnh, video, LLM) qua inference.sh CLI.
- nodejs-backend-patterns – Xây dựng dịch vụ backend Node.js sẵn sàng cho production với Express/Fastify, triển khai…