【发布时间】:2015-08-25 18:13:06
【问题描述】:
根据 Spring 4.2.0 文档第 5.5 项,我正在尝试使用 SimpUserRegistry 将用户列表连接到 websockets/STOMP 端点……但我对 Spring 很陌生,我只是不这样做'不知道在哪里/如何使用这个类。你能给我一个例子或指出正确的方向吗?
【问题讨论】:
标签: spring spring-mvc spring-websocket
根据 Spring 4.2.0 文档第 5.5 项,我正在尝试使用 SimpUserRegistry 将用户列表连接到 websockets/STOMP 端点……但我对 Spring 很陌生,我只是不这样做'不知道在哪里/如何使用这个类。你能给我一个例子或指出正确的方向吗?
【问题讨论】:
标签: spring spring-mvc spring-websocket
只需注入 SimpUserRegistry 作为依赖项。这是打印所有连接用户的用户名的示例:
@Autowired private SimpUserRegistry userRegistry;
public void printConnectedUsers() {
userRegistry.getUsers().stream()
.map(u -> u.getName())
.forEach(System.out::println);
}
【讨论】:
刚刚在与一个类似的问题作斗争 - 我想我会将这些发现留给未来的旅行者。
我试图使用包含上述 Autowired SimpUserRegistry 的 WebSocketSecurityInterceptor 来决定应该发送哪些消息。这涉及在WebSocketConfig 中设置拦截器;因为我需要 Autowired 字段,所以我不能像往常一样使用拦截器的构造函数。
@Component
public class WebSocketSecurityInterceptor implements ChannelInterceptor {
@Autowired
private SimpUserRegistry simpUserRegistry;
...other stuff
}
和
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractSecurityWebSocketMessageBrokerConfigurer {
@Autowired
private WebSocketSecurityInterceptor webSocketSecurityInterceptor;
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/stream");
config.configureBrokerChannel().setInterceptors(webSocketSecurityInterceptor);
}
不幸的是,由于初始化顺序的一些怪癖,当您将类自动装配到WebSocketConfig 时,configureMessageBroker(MessageBrokerRegistry config) 不再运行,因此没有添加拦截器。
我们能找到的唯一方法是在应用程序上下文中四处翻找正确的 bean:
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractSecurityWebSocketMessageBrokerConfigurer {
@Autowired private ApplicationContext applicationContext;
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/stream");
config.configureBrokerChannel().setInterceptors(config.configureBrokerChannel().setInterceptors(applicationContext.getBean(WebSocketSecurityInterceptor.class));
}
【讨论】: