gpt4 book ai didi

java - 使用外部消息代理的 Spring 作为代理中继

转载 作者:搜寻专家 更新时间:2023-10-31 20:34:09 24 4
gpt4 key购买 nike

我想使用 Spring Messaging 为我的 webapp 的登录用户创建一个实时通知系统。

我定义了一个 AbstractWebSocketMessageBrokerConfigurer 如下:

@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/notifications").withSockJS()
.setSessionCookieNeeded(true)
.setWebSocketEnabled(true);
}

@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/topic/", "/queue/");
}

并且,根据文档:

An application can send messages targeting a specific user. Spring’s STOMP support recognizes destinations prefixed with "/user/". For example, a client might subscribe to the destination "/user/queue/position-updates". This destination will be handled by the UserDestinationMessageHandler and transformed into a destination unique to the user session, e.g. "/queue/position-updates-user123". This provides the convenience of subscribing to a generically named destination while at the same time ensuring no collisions with other users subscribing to the same destination so that each user can receive unique stock position updates.

On the sending side messages can be sent to a destination such as "/user/{username}/queue/position-updates", which in turn will be translated by the UserDestinationMessageHandler into one or more destinations, one for each session associated with the user. This allows any component within the application to send messages targeting a specific user without necessarily knowing anything more than their name and the generic destination. This is also supported through an annotation as well as a messaging template.

通过向 /user/{username}/queue/something 发送消息,它将仅传递给由 {username} 标识的特定用户。

现在,我正在寻找一个允许我使用外部Message Broker(例如,RabbitMQ)的解决方案,Spring 就像Broker中继:

registry.enableStompBrokerRelay("/topic/", "/queue/");

在 Spring 中配置外部消息代理之后:

  • 是否可以使用 channel /user/{username/}/queue/something 在 Message Broker 上发送消息?如果是,怎么做?
  • 通过使用 channel /user/{username/}/queue/something 在 Message Broker 上发送消息,Spring 是否能够仅将该消息发送到 {username} code> 根据当前 Principal?

最佳答案

是的,如果启用外部代理,每个@MessageMapping 返回值都将序列化为 JSON 并发送到代理,请查看 Flow of Messages section引用文档的更多详细信息。所以它与简单代理基本相同。

你也可以注入(inject) SimpMessagingTemplateSimpMessageSendingOperations bean,就像在我的 OpenSnap example application 中完成的一样.您可以在 Controller 中使用它,也可以在纯推送上下文中的任何其他类中使用它。

您可以通过将 Principal 参数添加到您的 @MessageMapping 或 @SubscribeMapping 处理程序方法来检索主体,就像完成一样 here , 当前本金将被自动注入(inject)。

关于java - 使用外部消息代理的 Spring 作为代理中继,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25681520/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com