Video in progress
What is `@SubscribeMapping`, and how does it differ from a plain `@MessageMapping` and from a broker subscription?
@SubscribeMapping runs once when a client SUBSCRIBEs to a /app/... address, and sends the returned value straight to that session, bypassing the broker. It's handy for request-reply like "I subscribed, give me the initial state", while later updates still come through /topic.
📖 Answer
Example: a client opened a chat room and needs to see the last 50 messages. You could also make a REST request, but it's convenient to have everything inside one STOMP connection:
@Controller
class RoomController {
@SubscribeMapping("/room.{id}.history")
List<ChatMessage> history(@DestinationVariable long id, Principal user) {
access.checkMember(user, id);
return messages.lastN(id, 50);
}
}
client.subscribe('/app/room.42.history', m => renderHistory(JSON.parse(m.body)));
client.subscribe('/topic/room.42', m => append(JSON.parse(m.body)));
The differences:
@MessageMappingruns when the client doesSEND, while@SubscribeMappingruns when it doesSUBSCRIBE.- The reply of a
@MessageMappinggoes by default to the broker via/topic/...and is distributed to all subscribers. The reply of a@SubscribeMappinggoes directly to the requesting session only, throughclientOutboundChannel. If you add@SendToto the method, this behavior changes and the reply goes to the broker. - A
/app/...subscription isn't registered in the broker. It's a "one-shot" reply, and nothing arrives at that address afterward.
A trap: history and the live stream are separate subscriptions. If you subscribe to /topic/room.42 later, a message in between can slip through. I subscribe to /topic first and buffer what arrives, then request the history and merge by seq.
One more thing: in your Spring Security rules, don't forget simpSubscribeDestMatchers for /app/room.*.history. This is a subscription too, not a SEND.
Sign up to mark studied questions and save your progress.