问题
According with the Spring 4.2.0 documentation, item 5.5, I'm trying to use SimpUserRegistry to get the users list connected to an websockets/STOMP endpoint ...but I'm pretty new on Spring and I just don't know where/how to use this class. Can you provide me an example or point me in the right direction?
回答1:
Just inject SimpUserRegistry
as a dependency. Here's an example on printing the username of all connected users:
@Autowired private SimpUserRegistry userRegistry;
public void printConnectedUsers() {
userRegistry.getUsers().stream()
.map(u -> u.getName())
.forEach(System.out::println);
}
回答2:
Just been battling a similar issue - thought I'd leave the findings here for future travellers.
I was trying to use a WebSocketSecurityInterceptor
that contained the above Autowired SimpUserRegistry
in order to make decisions about which messages should be sent. This involved setting the interceptor in the WebSocketConfig
; because I needed the Autowired field, I couldn't just use the interceptor's constructor like normal.
@Component
public class WebSocketSecurityInterceptor implements ChannelInterceptor {
@Autowired
private SimpUserRegistry simpUserRegistry;
...other stuff
}
and
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractSecurityWebSocketMessageBrokerConfigurer {
@Autowired
private WebSocketSecurityInterceptor webSocketSecurityInterceptor;
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/stream");
config.configureBrokerChannel().setInterceptors(webSocketSecurityInterceptor);
}
Unfortunately in the above, due to some quirk of initialisation order, when you Autowire classes into WebSocketConfig
, the configureMessageBroker(MessageBrokerRegistry config)
is no longer run, and so the interceptor is not added.
The only way round we could find is rummaging around horribly in the application context to get the right bean instead:
@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));
}
来源:https://stackoverflow.com/questions/32211170/spring-4-2-0-how-to-use-simpuserregistry