根据Spring 4.2.0文档中的第5.5条,我想使用SimpUserRegistry来获取连接到Websockets / STOMP端点的用户列表...但我对Spring还很陌生,不知道在哪里/如何使用此类。你能给我提供一个例子或者指点我吗?
只需将 SimpUserRegistry
注入为依赖项即可。以下是一个示例,打印出所有连接用户的用户名:
@Autowired private SimpUserRegistry userRegistry;
public void printConnectedUsers() {
userRegistry.getUsers().stream()
.map(u -> u.getName())
.forEach(System.out::println);
}
我曾经遇到过类似的问题,现在我把解决方法留在这里,以便未来的使用者参考。
我尝试使用一个包含上述自动装配 SimpUserRegistry
的 WebSocketSecurityInterceptor
来决定哪些消息应该被发送。这需要在 WebSocketConfig
中设置拦截器;由于我需要使用自动装配字段,所以我不能像通常那样使用拦截器的构造函数。
@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));
}