Azure 沟通聊天 Java SDK
Azure Communication Chat (Java)
构建具有会话管理、消息传递、参与者管理和已读回执功能的实时聊天应用程序。
安装
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-communication-chat</artifactId>
<version>1.6.0</version>
</dependency>客户端创建
import com.azure.communication.chat.ChatClient;
import com.azure.communication.chat.ChatClientBuilder;
import com.azure.communication.chat.ChatThreadClient;
import com.azure.communication.common.CommunicationTokenCredential;
// ChatClient 需要 CommunicationTokenCredential(用户访问令牌)
String endpoint = "https://<resource>.communication.azure.com";
String userAccessToken = "<user-access-token>";
CommunicationTokenCredential credential = new CommunicationTokenCredential(userAccessToken);
ChatClient chatClient = new ChatClientBuilder()
.endpoint(endpoint)
.credential(credential)
.buildClient();
// 异步客户端
ChatAsyncClient chatAsyncClient = new ChatClientBuilder()
.endpoint(endpoint)
.credential(credential)
.buildAsyncClient();
核心概念
| 类 | 用途 |
|-------|---------|
| ChatClient | 创建/删除聊天会话,获取会话客户端 |
| ChatThreadClient | 会话内的操作(消息、参与者、回执) |
| ChatParticipant | 聊天会话中的用户,包含显示名称 |
| ChatMessage | 消息内容、类型、发送者信息、时间戳 |
| ChatMessageReadReceipt | 每个参与者的已读回执跟踪 |
创建聊天会话
import com.azure.communication.chat.models.*;
import com.azure.communication.common.CommunicationUserIdentifier;
import java.util.ArrayList;
import java.util.List;
// 定义参与者
List<ChatParticipant> participants = new ArrayList<>();
ChatParticipant participant1 = new ChatParticipant()
.setCommunicationIdentifier(new CommunicationUserIdentifier("<user-id-1>"))
.setDisplayName("Alice");
ChatParticipant participant2 = new ChatParticipant()
.setCommunicationIdentifier(new CommunicationUserIdentifier("<user-id-2>"))
.setDisplayName("Bob");
participants.add(participant1);
participants.add(participant2);
// 创建会话
CreateChatThreadOptions options = new CreateChatThreadOptions("Project Discussion")
.setParticipants(participants);
CreateChatThreadResult result = chatClient.createChatThread(options);
String threadId = result.getChatThread().getId();
// 获取会话客户端以进行操作
ChatThreadClient threadClient = chatClient.getChatThreadClient(threadId);
发送消息
// 发送文本消息
SendChatMessageOptions messageOptions = new SendChatMessageOptions()
.setContent("Hello, team!")
.setSenderDisplayName("Alice")
.setType(ChatMessageType.TEXT);
SendChatMessageResult sendResult = threadClient.sendMessage(messageOptions);
String messageId = sendResult.getId();
// 发送 HTML 消息
SendChatMessageOptions htmlOptions = new SendChatMessageOptions()
.setContent("<strong>Important:</strong> Meeting at 3pm")
.setType(ChatMessageType.HTML);
threadClient.sendMessage(htmlOptions);
获取消息
import com.azure.core.util.paging.PagedIterable;
// 列出所有消息
PagedIterable<ChatMessage> messages = threa
dClient.listMessages();
for (ChatMessage message : messages) {
System.out.println("ID: " + message.getId());
System.out.println("Type: " + message.getType());
System.out.println("Content: " + message.getContent().getMessage());
System.out.println("Sender: " + message.getSenderDisplayName());
System.out.println("Created: " + message.getCreatedOn());
// 检查是否已编辑或删除
if (message.getEditedOn() != null) {
System.out.println("Edited: " + message.getEditedOn());
}
if (message.getDeletedOn() != null) {
System.out.println("Deleted: " + message.getDeletedOn());
}
}
// 获取特定消息
ChatMessage message = threadClient.getMessage(messageId);
更新和删除消息
// 更新消息
UpdateChatMessageOptions updateOptions = new UpdateChatMessageOptions()
.setContent("Updated message content");
threadClient.updateMessage(messageId, updateOptions);
// 删除消息
threadClient.deleteMessage(messageId);
管理参与者
// 列出参与者
PagedIterable<ChatParticipant> participants = threadClient.listParticipants();
for (ChatParticipant participant : participants) {
CommunicationUserIdentifier user =
(CommunicationUserIdentifier) participant.getCommunicationIdentifier();
System.out.println("User: " + user.getId());
System.out.println("Display Name: " + participant.getDisplayName());
}
// 添加参与者
List<ChatParticipant> newParticipants = new ArrayList<>();
newParticipants.add(new ChatParticipant()
.setCommunicationIdentifier(new CommunicationUserIdentifier("<new-user-id>"))
.setDisplayName("Charlie")
.setShareHistoryTime(OffsetDateTime.now().minusDays(7))); // 共享过去 7 天的历史记录
threadClient.addParticipants(newParticipants);
// 移除参与者
CommunicationUserIdentifier userToRemove = new CommunicationUserIdentifier("<user-id>");
threadClient.removeParticipant(userToRemove);
已读回执
// 发送已读回执
threadClient.sendReadReceipt(messageId);
// 获取已读回执
PagedIterable<ChatMessageReadReceipt> receipts = threadClient.listReadReceipts();
for (ChatMessageReadReceipt receipt : receipts) {
System.out.println("Message ID: " + receipt.getChatMessageId());
System.out.println("Read by: " + receipt.getSenderCommunicationIdentifier());
System.out.println("Read at: " + receipt.getReadOn());
}
输入通知
import com.azure.communication.chat.models.TypingNotificationOptions;
// 发送输入通知
TypingNotificationOptions typingOptions = new TypingNotificationOptions()
.setSenderDisplayName("Alice");
threadClient.sendTypingNotificationWithResponse(typingOptions, Context.NONE);
// 简单的输入通知
threadClient.sendTypingNotification();
线程操作
// 获取线程属性
ChatThreadProperties properties = threadClient.getProperties();
System.out.println("Topic: " + properties.getTopic());
System.out.println("Created: " + properties.getCreatedOn());
// 更新主题
threadClient.updateTopic("New Project Discussion Topic");
// 删除线程
chatClient.deleteChatThread(threadId);
列出线程
// 列出用户的所有聊天线程
PagedIterable<ChatThreadItem> threads = chatClient.listChatThreads();
for (ChatThreadItem thread : threads) {
System.out.println("Thread ID: " + thread.getId());
System.out.println("Topic: " + thread.getTopic());
System.out.println("...");
}
t.println("Last message: " + thread.getLastMessageReceivedOn());
}
## 分页import com.azure.core.http.rest.PagedResponse;
// 对消息进行分页
int maxPageSize = 10;
ListChatMessagesOptions listOptions = new ListChatMessagesOptions()
.setMaxPageSize(maxPageSize);
PagedIterable<ChatMessage> pagedMessages = threadClient.listMessages(listOptions);
pagedMessages.iterableByPage().forEach(page -> {
System.out.println("Page status code: " + page.getStatusCode());
page.getElements().forEach(msg ->
System.out.println("Message: " + msg.getContent().getMessage()));
});
## 错误处理import com.azure.core.exception.HttpResponseException;
try {
threadClient.sendMessage(messageOptions);
} catch (HttpResponseException e) {
switch (e.getResponse().getStatusCode()) {
case 401:
System.out.println("Unauthorized - check token");
break;
case 403:
System.out.println("Forbidden - user not in thread");
break;
case 404:
System.out.println("Thread not found");
break;
default:
System.out.println("Error: " + e.getMessage());
}
}
## 消息类型
| 类型 | 描述 |
|------|-------------|
| TEXT | 普通聊天消息 |
| HTML | HTML 格式消息 |
| TOPIC_UPDATED | 系统消息 - 主题已更改 |
| PARTICIPANT_ADDED | 系统消息 - 参与者已加入 |
| PARTICIPANT_REMOVED | 系统消息 - 参与者已离开 |
环境变量
最佳实践
1. 令牌管理 - 用户令牌会过期;请使用
CommunicationTokenRefreshOptions 实现刷新逻辑。
2. 分页 - 对于大型会话,请在 listMessages(options) 中使用 maxPageSize。
3. 共享历史记录 - 在添加参与者时设置 shareHistoryTime 以控制消息可见性。
4. 消息类型 - 将系统消息(如 PARTICIPANT_ADDED` 等)与用户消息区分开。5. 已读回执 - 仅在用户实际查看消息时发送回执。
触发词
- "chat application Java", "real-time messaging Java"
- "chat thread", "chat participants", "chat messages"
- "read receipts", "typing notifications"
- "Azure Communication Services chat"
使用场景
本技能适用于执行概览中所描述的工作流或操作。局限性
- 仅在任务与上述范围明确匹配时使用此技能。
- 不要将输出视为针对特定环境的验证、测试或专家评审的替代方案。
- 如果缺少必要的输入、权限、安全边界或成功标准,请停止并请求澄清。