Spring Boot - Websockets - How to see subscribers

瘦欲@ 提交于 2019-12-23 01:52:32

问题


I'm working on a websocket application where I'm trying to have one websocket that feeds information in, and then outputs to subscribers to the endpoint. I've figure that out, but I'm wondering if there is a way to see what subscribers are subscribed and to what path?

Here is a code sample of what I'm working on.

@Autowired
private SimpMessagingTemplate template;

@MessageMapping("/{companyId}/{departmentId}")
@SendTo("/{companyId}/{departmentId}")
public void companyInformation(@DestinationVariable String companyId, @DestinationVariable String departmentId, CompanyMessage companyMessage){

    String destination = "/" + companyId + "/" + departmentId;
    template.convertAndSend(
          destination, processCompanyMessage(companyMessage, departmentId));
}

The idea is that the information poster sends companyMessage object to the @MessageMapping endpoint, the companyId and departmentId are retrieved from this mapping.

This message is then processed based on what the departmentId is and is posted to every department that has an active subscriber to the @SendTo path.

e.g.

There are 3 websocket subscribers, /smallCompany/booking, /smallCompany/sales, /smallCompany/inventory.
@MessageMapping gets a message from /smallCompany/sales. The method processes the message based on the departmentId and posts to EVERY subscriber with the same /{companyId}, even if the /{departmentId} differs.

Any ideas if this is possible, and if not, any ideas to push me in the right direction would be great.


回答1:


I know it's too late to answer! but I saw this question now! So, to guide others that will see this question, I should say:

You have several solutions:

1- SimpUserRegistry:

@Autowired private SimpUserRegistry simpUserRegistry;

public Set<SimpUser> getUsers() { 
    return simpUserRegistry.getUsers();
}

Check this link: Is there a Spring WebSocketSession repository?

2- Global list:

You've certainly configured the web-socket in spring boot, so, probably you have a derived class from WebSocketMessageBrokerConfigurer, with override configureClientInboundChannel to call setInterceptors...

You should implement custom interceptor derived from ChannelInterceptorAdapter and override preSend to access MessageHeaderAccessor.getAccessor(...).command
These commands defined in StompCommand (CONNECT, DISCONNECT, SUBSCRIBE, UNSUBSCRIBE,...)

By checking accessor.command with StompCommand.SUBSCRIBE/UNSUBSCRIBE you can create and sync a global static list of subscribers, and use it everywhere you need.

3- Other solution:

Check this link:
how to capture subscribe event in my webSocket server with Spring 4



来源:https://stackoverflow.com/questions/42923461/spring-boot-websockets-how-to-see-subscribers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!