我正在使用 Spring 框架,我有一个工作的 websocket Controller ,如下所示:
@Controller
public class GreetingController {
@MessageMapping("/hello")
@SendTo("/topic/greetings")
public Greeting greeting(HelloMessage message) throws InterruptedException {
return new Greeting("Hello, " + message.getName() + "!");
}
}
我也有这个配置:
@Configuration
@EnableWebSocketMessageBroker
public class HelloWebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/hello").withSockJS();
}
}
那部分效果很好!我可以使用 Stomp.js 在两个或多个浏览器之间成功发送和接收消息。这是不起作用的部分。我实现了一个 ServletContextListener
,其中包含一个自定义对象,为简单起见,我将其称为“通知程序”。通知程序监听服务器端发生的某些事件。然后它调用“通知”方法,该方法应该将有关事件的详细信息发送给所有客户端。但是,它不起作用。
@WebListener
public class MessageListener implements ServletContextListener, Notifiable {
private Notifier notifier;
@Autowired
private SimpMessagingTemplate messageSender;
public MessageListener() {
notifier = new Notifier(this);
}
public void contextInitialized(ServletContextEvent contextEvent) {
WebApplicationContextUtils
.getRequiredWebApplicationContext(contextEvent.getServletContext())
.getAutowireCapableBeanFactory()
.autowireBean(this);
notifier.start();
}
public void contextDestroyed(ServletContextEvent contextEvent) {
notifier.stop();
}
public void notify(NotifyEvent event) {
messageSender.convertAndSend("/topic/greetings", new Greeting("Hello, " + event.subject + "!"));
}
}
我没有得到异常。 SimpMessagingTemplate
已被 Spring 成功注入(inject),因此它不为空。我已经能够进入 Spring 代码并发现在使用 SimpMessagingTemplate
时 SimpleBrokerMessageHandler
的 subscriptionRegistry
是空的。因此它必须是与 Controller 正在使用的实例不同的实例。我怎样才能获得 Controller 使用的相同 subscriptionRegistry
?
最佳答案
解决方案是使用 Spring 的 ApplicationListener
类而不是 ServletContextListener
,并专门监听 ContextRefreshedEvent
。
这是我的工作示例:
@Component
public class MessagingApplicationListener implements ApplicationListener<ContextRefreshedEvent>, Notifiable {
private final NotifierFactor notifierFactory;
private final MessageSendingOperations<String> messagingTemplate;
private Notifier notifier;
@Autowired
public MessagingApplicationListener(NotifierFactor notifierFactory, MessageSendingOperations<String> messagingTemplate) {
this.notifierFactory = notifierFactory;
this.messagingTemplate = messagingTemplate;
}
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
if (notifier == null) {
notifier = notifierFactory.create(this);
notifier.start();
}
}
public void notify(NotifyEvent event) {
messagingTemplate.convertAndSend("/topic/greetings", new Greeting("Hello, " + event.subject + "!"));
}
@PreDestroy
private void stopNotifier() {
if (notifier != null) {
notifier.stop();
}
}
}
关于java - 通过 ServletContextListener 中的 SimpMessagingTemplate 向所有客户端发送消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25561741/