Video in progress
How do you send a message from the server to a client using SimpMessagingTemplate?
Inject the SimpMessagingTemplate bean and call convertAndSend("/topic/...", payload). This sends the message to every client subscribed to that destination, and you can call it from any service or scheduled job.
📖 Answer
@SendTo only works as a reply to a client message. Often, though, the message originates elsewhere: a payment was confirmed, an event came from Kafka, a cron job ran.
@Service
public class OrderNotifier {
private final SimpMessagingTemplate messaging;
public OrderNotifier(SimpMessagingTemplate messaging) {
this.messaging = messaging;
}
public void statusChanged(Order order) {
// to everyone who has this order's page open
messaging.convertAndSend("/topic/orders/" + order.getId(),
new OrderStatusDto(order.getId(), order.getStatus()));
}
}
The payload is converted to JSON through Jackson. To send to a single user, use convertAndSendToUser(username, "/queue/notifications", dto).
Keep one thing in mind: this call hands the message to the broker and returns right away. It doesn't tell you whether the client actually received it. Save important messages to the database as well.
Sign up to mark studied questions and save your progress.