
mercure 是一个开放、高效且易于使用的协议,专为构建实时、响应式 web 应用程序而设计。它基于 server-sent events (sse) 技术,允许服务器向客户端推送更新,非常适合聊天应用、通知系统、仪表盘等场景。symfony 框架通过其 mercure bundle 提供了与 mercure hub 的无缝集成,极大地简化了实时功能的开发。
要在 Symfony 项目中使用 Mercure,首先需要安装并运行 Mercure Hub 服务器。
从 Mercure 的 GitHub 发布页面(例如 https://github.com/dunglas/mercure/releases)下载适用于您操作系统的最新版本。对于 Windows 系统,通常会下载类似 mercure_X.Y.Z_Windows_amd64.zip 的文件。
将下载的压缩包解压到一个您方便管理的目录。解压后,您会得到一个 mercure.exe 可执行文件以及一个默认的 Caddyfile.dev 配置文件。
Mercure Hub 使用 Caddy 作为其底层的 HTTP 服务器。在运行 Mercure Hub 之前,您需要设置 JWT 密钥,用于发布者和订阅者的认证。在 PowerShell 中,可以使用以下命令运行 Mercure Hub:
$env:MERCURE_PUBLISHER_JWT_KEY='!ChangeMe!'; $env:MERCURE_SUBSCRIBER_JWT_KEY='!ChangeMe!'; .\mercure.exe run -config Caddyfile.dev
注意事项:
成功运行后,您会在终端看到类似以下输出,表明 Mercure 服务器已启动并正在监听:
2021/11/16 01:39:58.029 INFO http server is listening only on the HTTPS port but has no TLS connection policies; adding one to enable TLS {"server_name": "srv0", "https_port": 443}
...
2021/11/16 01:39:58.135 INFO http enabling automatic TLS certificate management {"domains": ["localhost"]}
...
2021/11/16 01:39:58.143 INFO serving initial configuration这些日志表明 Caddy 服务器正在处理 HTTPS 配置,并已启用自动 TLS 证书管理,服务正在正常运行。
在 Mercure Hub 运行的同时,您需要在 Symfony 项目中安装并配置 Mercure Bundle。
在您的 Symfony 项目根目录执行 Composer 命令:
composer require symfony/mercure
安装完成后,Symfony 会自动在您的 .env 文件中添加 Mercure 相关的配置项。您需要根据实际情况进行调整:
# See https://symfony.com/doc/current/mercure.html#configuration # The URL of the Mercure hub, used by the app to publish updates (can be a local URL) MERCURE_URL=https://127.0.0.1:8000/.well-known/mercure # The public URL of the Mercure hub, used by the browser to connect MERCURE_PUBLIC_URL=https://127.0.0.1:8000/.well-known/mercure # The secret used to sign the JWTs MERCURE_JWT_SECRET="!ChangeMe!" ###< symfony/mercure-bundle ###
关键配置项说明:
一个常见的误区是,在 Mercure Hub 运行后,尝试通过 https://localhost/.well-known/mercure 访问它。这通常会导致“Not Found”错误,因为 Mercure Hub 默认监听在特定的端口上(例如 8000),而不是标准的 HTTPS 端口 443。
当您在浏览器中看到类似以下错误时:
Not Found The requested URL was not found on this server. Apache/2.4.46 (Win64) OpenSSL/1.1.1h PHP/7.4.25 Server at localhost Port 443
这表明您的请求被默认监听 443 端口的 Apache 服务器(或其他 Web 服务器)捕获,而不是 Mercure Hub。
解决方案:
根据您在 .env 中 MERCURE_PUBLIC_URL 的配置,以及 Mercure Hub 实际监听的端口,您应该使用正确的端口号来访问 Mercure Hub。
例如,如果您的 MERCURE_PUBLIC_URL 配置为 https://127.0.0.1:8000/.well-known/mercure,那么在浏览器中访问时,也应该带上端口 8000:
https://localhost:8000/.well-known/mercure
正确访问时,您应该会看到一个空白页面,或者一个表示连接成功的消息(例如,如果 Mercure Hub 配置了默认欢迎页)。这表明您的浏览器已成功连接到 Mercure Hub。
通过遵循上述步骤和注意事项,您将能够成功在 Symfony 5 项目中配置和运行 Mercure,为您的应用程序添加强大的实时通信能力。
以上就是Symfony 5 与 Mercure 的实时通信配置指南的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号