我有这个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("/portfolio").withSockJS();
}
}
我通过SimpMessagingTemplate发送Kafka数据,如下所示:
public class KafkaReceiver {
@Autowired
private SimpMessagingTemplate simpMessagingTemplate;
@KafkaListener(topics = "metrics", groupId = "metrics")
public void receive(ConsumerRecord<?, ?> record) {
MetricRecord m = new MetricRecord(new Long(record.offset()), record.key().toString(), record.value().toString());
this.simpMessagingTemplate.convertAndSend("/topic/records", m.toString());
}
}
我有这个客户:
function connect() {
var socket = new SockJS('/portfolio/records');
var stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/records', function (message) {
console.log(message);
console.log(JSON.parse(message.body));
});
});
}
当我在浏览器中运行时,我收到以下错误:
Opening Web Socket...
GET http://localhost:9999/portfolio/records/info?t=1507027267841 404 (Not Found)
r._start @ sockjs.min.js:2
(anonymous) @ sockjs.min.js:2
setTimeout (async)
r @ sockjs.min.js:2
r @ sockjs.min.js:3
r @ sockjs.min.js:2
r._getReceiver @ sockjs.min.js:2
r.doXhr @ sockjs.min.js:2
(anonymous) @ sockjs.min.js:2
setTimeout (async)
r @ sockjs.min.js:2
r @ sockjs.min.js:2
connect @ metricsApp.js:2
onclick @ VM53 metrics:1
Whoops! Lost connection to http://localhost:9999/portfolio/records
有什么想法吗?我找不到比我更有效的解决方案。提前谢谢。
答案 0 :(得分:0)
检查此行:
var socket = new SockJS('/portfolio/records');
您应该将套接字连接到:
var socket = new SockJS('/${YourApplicationContextIfItExists}/${endPoint}')
假设您没有应用程序上下文,它应该是
var socket = new SockJS('/portfolio')
请注意可能还有其他问题,但我认为这可能会有所帮助。
答案 1 :(得分:0)
registry.addEndpoint("/portfolio").setAllowedOrigins("*").withSockJS();
您在 StompEndpoint 创建时尝试过吗?