使用Symfony UX Notify时通知功能无法正常工作求助
我正尝试使用Symfony UX Notify搭建通知功能,已参考对应文档配置了Mercure服务器。以下是我的配置及代码,但添加链接操作成功后通知并未弹出,恳请告知哪里配置错误或遗漏了步骤。
.env 配置
###> symfony/mercure-notifier ### MERCURE_DSN=mercure://default ###< symfony/mercure-notifier ### ###> symfony/mercure-bundle ### # 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=http://localhost:62635/.well-known/mercure # The public URL of the Mercure hub, used by the browser to connect MERCURE_PUBLIC_URL=http://localhost:62635/.well-known/mercure # The secret used to sign the JWTs MERCURE_JWT_SECRET= my jwt token here ###< symfony/mercure-bundle ###
notifier.yaml 配置
framework: notifier: chatter_transports: myMercureChatter: '%env(MERCURE_DSN)%'
控制器代码
use Symfony\Component\Notifier\Bridge\Mercure\MercureOptions; use Symfony\Component\Notifier\Exception\TransportExceptionInterface; use Symfony\Component\Notifier\Message\ChatMessage; use Symfony\Component\Notifier\ChatterInterface; class PageIndexController extends DefaultLayoutController { public function __construct( ThemeHelper $theme, private readonly EntityManagerInterface $entityManager, private readonly IndexLinkRepository $indexLinkRepository, private ChatterInterface $chatter ) { parent::__construct($theme); } // 其他控制器代码 // 创建通知的方法 #[Route('/new', name: 'app_page_index_new', methods: ['GET', 'POST'])] public function new(Request $request, ParameterBagInterface $parameterBag): Response { /** @var User $user */ $user = $this->getUser(); $dto = new IndexLinksDTO(); $form = $this->createForm(IndexLinksType::class, $dto, [ 'validation_groups' => ['basic'] ]); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $dto->setUser($user); $cost = $parameterBag->get('page_index_cost'); $totalCost = count($dto->getLinks()) * $cost; if ($user->getBalance() < $totalCost) { $this->addFlash('error', "您的代币不足以索引这些链接。索引一个链接需要$cost代币,请充值以获得高质量的链接索引服务。"); return $this->redirectToRoute('app_page_index_new'); } $entityManager = $this->entityManager; foreach ($dto->getLinks() as $link) { $indexLink = new IndexLink(); $indexLink->setUser($user); $indexLink->setUrl($link->getUrl()); $indexLink->setUserTokens($cost); $entityManager->persist($indexLink); } $user->setBalance($user->getBalance() - $totalCost); $entityManager->flush(); $message = (new ChatMessage( '成功!链接已添加至索引队列。', new MercureOptions(['/index/link-indexing']) ))->transport('myMercureChatter'); $this->chatter->send($message); return $this->redirectToRoute('app_page_index'); } return $this->render('pages/page_index/create.html.twig', [ 'form' => $form->createView(), ]); } }
TWIG 模板代码
{{ stream_notifications(['/index/link-indexing']) }}
可能的问题及解决方法
MERCURE_DSN 配置无效
当前MERCURE_DSN使用的是默认占位符mercure://default,需要替换为实际指向Mercure服务的完整DSN,格式如下:MERCURE_DSN=mercure://localhost:62635/.well-known/mercure?jwt=%env(MERCURE_JWT_SECRET)%确保DSN包含Mercure hub地址和正确的JWT密钥,否则Symfony无法连接到Mercure服务发送通知。
JWT密钥格式错误
检查MERCURE_JWT_SECRET的值,去掉开头的空格,确保它与Mercure服务器启动时使用的密钥完全一致。例如Mercure启动命令如果是mercure --jwt-key='your-secret-key',这里就填your-secret-key。重定向导致通知无法接收
控制器发送通知后立即执行重定向,此时浏览器已经离开包含stream_notifications的页面,无法建立Mercure连接接收消息。解决方法:- 在目标页面(
app_page_index对应的模板)也添加{{ stream_notifications(['/index/link-indexing']) }}; - 延迟重定向,确保通知已发送到Mercure;
- 临时改用Flash消息,同时保留实时通知逻辑。
- 在目标页面(
Mercure服务未正常运行
访问http://localhost:62635/.well-known/mercure,如果返回405 Method Not Allowed说明服务正常;如果无法访问,启动Mercure服务器并确认端口匹配。前端资源未正确加载
确认已安装symfony/ux-notify,并执行以下命令更新前端资源:php bin/console assets:install yarn install && yarn build # 或 npm install && npm run build缺少前端JS逻辑会导致
stream_notifications无法弹出通知。权限配置问题
如果Mercure服务器未开启匿名访问(--allow-anonymous),需要确保JWT包含订阅和发布/index/link-indexing主题的权限。JWT payload示例:{ "mercure": { "subscribe": ["/index/link-indexing"], "publish": ["/index/link-indexing"] } }查看日志排查错误
检查Symfony日志文件var/log/dev.log,如果发送通知时出现TransportException,日志会明确提示错误原因(如JWT无效、连接失败等)。
内容的提问来源于stack exchange,提问作者Оксана Третьякова

