我正在尝试使用 STOMP 将 WebSockets 支持添加到使用 XML 配置的 Spring MVC 应用程序中。到目前为止,一切进展顺利,我已经成功让 WebSockets 服务器进行监听,并且 stomp.js 可以连接到它并发送消息和接收响应。
我还没有设法开始工作的是支持服务器向客户端发送任意消息,这些消息不是对从客户端收到的消息的响应。这意味着到目前为止,这实际上只是 REST 的一个更复杂的版本,并不太有用。
我的 XML 配置如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:websocket="http://www.springframework.org/schema/websocket"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/websocket http://www.springframework.org/schema/websocket/spring-websocket.xsd">
<websocket:message-broker>
<websocket:stomp-endpoint path="/api/websocket/stomp" allowed-origins="*">
</websocket:stomp-endpoint>
<websocket:simple-broker prefix="/topic,/queue" />
<websocket:message-converters>
<bean class="org.springframework.messaging.converter.MappingJackson2MessageConverter">
<property name="objectMapper" ref="objectMapper" />
</bean>
</websocket:message-converters>
</websocket:message-broker>
<bean class="uk.co.grahamcox.webapp.DebugController">
<constructor-arg name="clock" ref="clock" />
<constructor-arg name="template" ref="brokerMessagingTemplate" />
</bean>
</beans>
(DebugController 是一个类,它有一个返回服务器时间的方法,作为 REST 和 WS 处理程序都可以正常工作)
启动时我得到:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'brokerMessagingTemplate' is defined
令人沮丧的是,IntelliJ 自动为我完成了“brokerMessagingTemplate”参考,我可以单击它到 AbstractMessageBrokerConfiguration 中的 @Bean 定义。
我假设我在 XML 中缺少一些配置来完成这项工作,但我无法在文档中找到这是什么。
有什么建议么?
支持服务器向客户端发送任意消息
不是对从客户收到的回复的回复。
向客户端发送消息的一种方法是让他们首先订阅一个主题 - 确保了解“应用程序目标前缀”和“代理前缀”之间的区别。在这种特殊情况下,您希望客户端订阅代理目标,然后您的服务器可以随时向所有这些客户端发送消息。
了解这一点的最好方法是查看参考文档中的消息流 http://docs.spring.io/spring-framework/docs/current/spring-framework-reference/html/websocket.html#websocket-stomp-message-flow.
要发送这些消息,您的应用程序代码需要一个消息模板。
您可以通过将表单 bean 名称切换为实际 bean 类型来修复代码示例SimpMessagingTemplate
.
<bean class="uk.co.grahamcox.webapp.DebugController">
<constructor-arg name="clock" ref="clock" />
<constructor-arg name="template" class="org.springframework.messaging.simp.SimpMessagingTemplate" />
</bean>
The 参考文档提到了 bean 名称 http://docs.spring.io/spring-framework/docs/current/spring-framework-reference/html/websocket.html#websocket-stomp-handle-send但在使用XML配置时似乎没有用这个名称注册。随意创建一个JIRA问题 https://jira.spring.io来改善这一点。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)