【发布时间】:2015-09-03 02:14:58
【问题描述】:
我使用 Stomp over SockJS 和 Spring 消息传递。当连接新用户时,我正在尝试向所有登录用户发送消息。所以首先这是我的听众:
@Component
public class SessionConnectedListener implements ApplicationListener<SessionConnectedEvent> {
private static final Logger log = LoggerFactory.getLogger(SessionConnectedListener.class);
@Autowired
private SimpMessagingTemplate template;
@Override
public void onApplicationEvent(SessionConnectedEvent event) {
log.info(event.toString());
// Not sure if it's sending...?
template.convertAndSend("/topic/login", "New user logged in");
}
}
我的 WebSocket 配置
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("chat").withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic", "/queue");
config.setApplicationDestinationPrefixes("/app");
}
}
我的 JS 配置
var socket = new SockJS('/chat');
stompClient = Stomp.over(socket);
stompClient.connect({}}, function(frame) {
// ... other working subscriptions
stompClient.subscribe("/topic/login", function(message) {
console.log(message.body);
});
});
我的问题是我的 template.convertAndSend() 在 ApplicationListener 中不起作用。但是,如果我将它放在使用 @MessageMapping 注释的 Controller 方法中,它将起作用,并且我将拥有一个控制台日志客户端。
所以我的问题是:template.convertAndSend() 可以在 ApplicationListener 中工作吗?如果是这样,怎么做?还是我错过了什么?
感谢您的帮助!
PS : 我的 log.info(event.toString());在 ApplicationListener 中工作 所以我知道我正在进入 onApplicationEvent() 方法。
【问题讨论】:
标签: spring spring-mvc sockjs spring-messaging stompjs