你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

适用于 Java 的 Azure Web PubSub 服务客户端库

Azure Web PubSub 服务 是一种 Azure 托管服务,可帮助开发人员轻松构建具有实时功能和发布-订阅模式的 Web 应用程序。 需要服务器和客户端之间或客户端之间的实时发布-订阅消息传送的任何方案都可以使用 Azure Web PubSub 服务。 通常需要从服务器轮询或提交 HTTP 请求的传统实时功能也可以使用 Azure Web PubSub 服务。

本文介绍 Azure Web PubSub 服务客户端库。

可以在服务器端应用中使用此库来管理 WebSocket 客户端连接,如下图所示:

溢出图显示使用服务客户端库的溢出。

使用此库可以:

  • 将消息发送到中心和组。
  • 向特定用户和连接发送消息。
  • 将用户和连接分组组织。
  • 关闭连接
  • 授予、撤销和检查现有连接的权限

有关详细信息,请参见:

入门指南

先决条件

导入软件包

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-messaging-webpubsub</artifactId>
    <version>1.0.0</version>
</dependency>

使用连接字符串创建 WebPubSubServiceClient

WebPubSubServiceClient webPubSubServiceClient = new WebPubSubServiceClientBuilder()
    .connectionString("{connection-string}")
    .hub("chat")
    .buildClient();

使用访问密钥创建 WebPubSubServiceClient

WebPubSubServiceClient webPubSubServiceClient = new WebPubSubServiceClientBuilder()
    .credential(new AzureKeyCredential("{access-key}"))
    .endpoint("<Insert endpoint from Azure Portal>")
    .hub("chat")
    .buildClient();

例子

将消息广播到整个中心

webPubSubServiceClient.sendToAll("Hello world!", WebPubSubContentType.TEXT_PLAIN);

将消息广播到一个组

webPubSubServiceClient.sendToGroup("java", "Hello Java!", WebPubSubContentType.TEXT_PLAIN);

向连接发送消息

webPubSubServiceClient.sendToConnection("myconnectionid", "Hello connection!", WebPubSubContentType.TEXT_PLAIN);

向用户发送消息

webPubSubServiceClient.sendToUser("Andy", "Hello Andy!", WebPubSubContentType.TEXT_PLAIN);

Troubleshooting

启用客户端日志记录

可以将环境变量设置为 AZURE_LOG_LEVEL 查看客户端库中的日志记录语句。 例如,设置 AZURE_LOG_LEVEL=2 将显示所有信息性、警告和错误日志消息。 日志级别可在此处找到: 日志级别

默认 HTTP 客户端

默认情况下,所有客户端库都使用 Netty HTTP 客户端。 添加上述依赖项将自动配置客户端库以使用 Netty HTTP 客户端。 HTTP 客户端 Wiki 中介绍了配置或更改 HTTP 客户端

默认 SSL 库

默认情况下,所有客户端库都使用 Tomcat 本机的 BoringSSL 库来实现 SSL 操作的本机级性能。 Boring SSL 库是一个 uber jar,包含适用于 Linux/macOS/Windows 的本机库,与 JDK 中的默认 SSL 实现相比,提供更好的性能。 有关详细信息,包括如何减小依赖项大小,请参阅 [性能优化][https://github.com/Azure/azure-sdk-for-java/wiki/Performance-Tuning]。

使用这些资源开始生成自己的应用程序: