azure-messaging-webpubsub-java
microsoft/skills
Azure Web PubSub SDK for Java를 사용하여 실시간 웹 애플리케이션을 구축하고, WebSocket 기반 메시징, 실시간 업데이트, 채팅, 서버에서 클라이언트로의 푸시 알림을 활성화합니다.
...모든 것을 확장하십시오자바용 Azure Web PubSub SDK
자바용 Azure Web PubSub SDK를 사용하여 실시간 웹 애플리케이션을 구축하세요.
설치
<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): 연결에 대한 논리적 격리 단위
- 그룹(Group): 허브 내의 연결 하위 집합
- 연결(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(
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("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();
오류 처리
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());
}
환경 변수
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. | 특정 그룹에 메시지 보내기 |
모범 사례
- 그룹 사용: 대상 메시징을 위해 연결을 그룹으로 구성하세요
- 사용자 ID: 사용자 수준 메시징을 위해 연결을 사용자 ID와 연관시키세요
- 토큰 만료: 보안을 위해 적절한 토큰 만료 시간을 설정하세요
- 역할: 최소한의 필요한 권한을 역할을 통해 부여하세요
- 허브 격리: 서로 다른 애플리케이션 기능에 대해 별도의 허브를 사용하세요
- 연결 관리: 비활성 연결을 정리하세요
트리거 구문
- "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
복사





집
