我一直在尝试让simpMessagingTemplate在Spring中发送到websocket,但无济于事。从对相关stackoverflow帖子和其他指南的了解中,我提供了必要的路径配置和映射。
我的代码如下所示:
RestController(我用来调用将消息发送到Websocket的消息):
@RestController
public class RestControllers {
@Autowired
private SimpMessagingTemplate template;
@RequestMapping("/test")
public String doTest() {
Message m = new Message();
m.setFrom("foo");
m.setText("bar");
template.convertAndSend("/app/chat/test-topic", m);
return m.toString();
}
}
控制器:
@Controller
public class ChatController
{
@MessageMapping("/chat/{topic}")
@SendTo("/topic/messages")
public OutputMessage send(@DestinationVariable("topic") String topic,
Message message) throws Exception
{
System.out.println("THE MESSAGE WAS RECEIVED:" + message.toString());
return new OutputMessage(message.getFrom(), message.getText(), topic);
}
}
配置:
@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) //?? alternative only?
{
registry.addEndpoint("/chat").setAllowedOrigins("*").withSockJS();
}
}