gpt4 book ai didi

java - SimpMessagingTemplate 不在 spring boot 中发送消息

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:08:40 26 4
gpt4 key购买 nike

大家好,我正在尝试向 Stomp 端点发送消息,但我没有收到任何消息。我正在使用 spring boot 和 stomp 以下是我的类(class)

@Controller
public class GreetingController {

@MessageMapping("/hello")
@SendTo("/topic/greetings")
public Greeting greeting(HelloMessage message) throws Exception {
System.out.println(message.getName());
Thread.sleep(13000); // simulated delay
return new Greeting("Hello, " + message.getName() + "!");
}

}

@Controller
public class Testcont {

@Autowired
private SimpMessagingTemplate messageSender;

@RequestMapping(value="/Users/get",method=RequestMethod.POST)
@ResponseBody
public String getUser(@RequestParam(value = "userId") String userId, @RequestParam(value = "password") String password, @RequestParam(value="port") String port, HttpServletRequest request) {
HelloMessage mess=new HelloMessage();
mess.setName(userId);
messageSender.convertAndSend("/app/hello",mess);
return "Success";

}

和我的 websocket 配置

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}

@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/hello").withSockJS();
}

}

我在控制台中没有收到任何错误。上面的代码在网络浏览器上运行良好。

最佳答案

SimpMessagingTemplate bean 完全用于 Broker 部分 (AbstractMessageBrokerConfiguration):

@Bean
public SimpMessagingTemplate brokerMessagingTemplate() {
SimpMessagingTemplate template = new SimpMessagingTemplate(brokerChannel());
String prefix = getBrokerRegistry().getUserDestinationPrefix();
if (prefix != null) {
template.setUserDestinationPrefix(prefix);
}

由于您没有将消息发送到代理目的地(在您的情况下为 /app/),因此 AbstractBrokerMessageHandler.checkDestinationPrefix(destination) 会忽略此类消息。

如果您希望通过相同的@MessageMapping 处理该内部消息,您应该直接使用clientInboundChannel,它由SimpAnnotationMethodMessageHandler< 提供:

@Bean
public SimpAnnotationMethodMessageHandler simpAnnotationMethodMessageHandler() {
SimpAnnotationMethodMessageHandler handler = createAnnotationMethodMessageHandler();
handler.setDestinationPrefixes(getBrokerRegistry().getApplicationDestinationPrefixes());

我想您可以为 clientInboundChannel 创建自己的 SimpMessagingTemplate 实例,类似于 brokerMessagingTemplate bean。你会没事的。

关于java - SimpMessagingTemplate 不在 spring boot 中发送消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36456458/

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