Skip to content

[feat]: Real-Time Stock Price Updates with WebSockets #11

@0PrashantYadav0

Description

@0PrashantYadav0

Description

  • Detailed Description:
    Enabling real-time stock price updates using WebSockets allows the application to push live updates to the client without requiring constant polling. This enhancement improves the user experience by providing instantaneous updates.
  • How to Solve:
    1. Configure WebSocket Support:
      Create a configuration class and annotate it with @EnableWebSocketMessageBroker:
      @Configuration
      @EnableWebSocketMessageBroker
      public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
          @Override
          public void configureMessageBroker(MessageBrokerRegistry config) {
              config.enableSimpleBroker("/topic");
              config.setApplicationDestinationPrefixes("/app");
          }
      
          @Override
          public void registerStompEndpoints(StompEndpointRegistry registry) {
              registry.addEndpoint("/ws").setAllowedOrigins("*").withSockJS();
          }
      }
    2. Create a WebSocket Controller:
      Develop a controller that periodically retrieves stock prices and broadcasts them:
      @Controller
      public class StockWebSocketController {
          @Autowired
          private SimpMessagingTemplate messagingTemplate;
      
          @Scheduled(fixedRate = 5000)
          public void sendStockUpdates() {
              // Logic to retrieve the latest stock prices
              String update = getLatestStockUpdate();
              messagingTemplate.convertAndSend("/topic/stockPrices", update);
          }
          
          private String getLatestStockUpdate() {
              // Fetch and format the latest stock data as needed
              return "{\"symbol\":\"AAPL\",\"price\":150.25}";
          }
      }
    3. Client-Side Integration:
      On the client side, use a WebSocket client (such as SockJS and Stomp.js) to subscribe to /topic/stockPrices and update the UI in real-time.
    4. Test End-to-End:
      Verify that clients receive real-time updates without polling.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions