cgraf
cgraf

Reputation: 165

Spring 4.2.0 - How to use SimpUserRegistry

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?

Upvotes: 6

Views: 5659

Answers (2)

fahran
fahran

Reputation: 163

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));
    }

Upvotes: 3

Sergi Almar
Sergi Almar

Reputation: 8414

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);
}

Upvotes: 10

Related Questions