简体   繁体   中英

Spring Boot endpoints + webSocket

I'm developing application which has regular endpoints for CRUD operations on entities (I'm injecting controller), the flow of the application should make entities' properties constatly changing so I will be in need to inform front end about those changes in real time. That is why I have registered Web Socket

@Configuration 
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry webSocketHandlerRegistry) {
    webSocketHandlerRegistry.addHandler(new PositionHandler(),"/positions").setAllowedOrigins("*");
}

class PositionHandler extends TextWebSocketHandler {

    private List<WebSocketSession> sessions = new CopyOnWriteArrayList<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
       sessions.add(session);
       while(session.isOpen()){
          HERE I WOULD LIKE TO ACCESS METHOD FOR  CONTROLLER
       }


        super.afterConnectionEstablished(session);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
       for(WebSocketSession s: sessions){
            session.sendMessage(message);
        }

        super.handleTextMessage(session, message);
    }
}

}

inside afterConnectionEstablished I would like to use methods from controller which is injected into ordinary @RestController class. Is there any possibility to do it? And if not how should I refactor. PS WebSocket works.

You can yous dependency injection in your handler (@Autowired annotation) and invoke method from rest controller. But why you want do this? Do you have business logic inside controller?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM