我希望我的代码侦听Rabbitmq,然后在websocket上将该消息显示为toater
到目前为止,我已经能够收听到我在日志中看到的消息, 但是当我检查它时,可以看到我的websocket已打开,已连接并已订阅,但未收到任何消息,
我遵循了这些教程 https://spring.io/guides/gs/messaging-stomp-websocket/ 我是websocket和js的新手。
这是我到目前为止写的。
WebSocketConfig.java:
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/notifications");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/v1/quizzes").withSockJS();
}
}
这是我的消费者
@Component
public class EventConsumer {
private Logger logger = LoggerFactory.getLogger(EventConsumer.class);
@Autowired
NotificationService notificationService;
int i;
@StreamListener("Event")
public void receivedEvent(String message) {
notificationService.sendNotification(message);
logger.info("EVENT Received "+ ++i);
}
}
这是我发送给订阅者的方式
@Service
public class NotificationService {
private Logger logger = LoggerFactory.getLogger(NotificationService.class);
@SendTo("/notifications")
public String sendNotification(String message) {
logger.info("IN SEND NOTIFICATION " + message);
return message;
}
}
app.js
var ws;
var stompClient;
ws = new SockJS("/v1/quizzes");
stompClient = Stomp.over(ws);
stompClient.connect({}, function(frame){
stompClient.subscribe("/notifications", function(message){
Materialize.toast(message)
console.log("received " + message);
});
}, function(error) {
console.log("Stomp protocol error." + error);
});
和此index.html
<!DOCTYPE html>
<html>
<head>
<title>!WebSocket</title>
<script src="/webjars/jquery/jquery.min.js"></script>
<script src="/webjars/sockjs-client/sockjs.min.js"></script>
<script src="/webjars/stomp-websocket/stomp.min.js"></script>
<script src="/app.js"></script>
</head>
<body>
<noscript><h2 style="color: #ff0000">Seems your browser doesn't support Javascript! Websocket relies
on Javascript being
enabled. Please enable Javascript and reload this page!</h2></noscript>
<div class="col-md-6">
<form class="form-inline">
<div class="form-group">
<label>WebSocket connection</label>
</div>
</form>
</div>
</body>
</html>