Mensajería dirigida a usuarios específicos
Envíe mensajes privados por usuario mediante STOMP usando destinos de usuario, @SendToUser y SimpMessagingTemplate.convertAndSendToUser.
Mensajería dirigida a usuarios específicos es una lección gratuita de WebSockets & Real-Time Systems with Spring en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de WebSockets & Real-Time Systems with Spring, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de WebSockets & Real-Time Systems with Spring incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
Beyond Broadcasts
So far messages went to a /topic that every subscriber receives. Real apps also need private messages: a chat whisper, a personal notification, an order update for one customer.
User Destinations
Spring supports the /user destination prefix. When a client subscribes to /user/queue/notifications, Spring rewrites it to a unique, per-session queue so only that user gets the message.
Where the Principal Comes From
Targeted messaging needs to know who a session is. The Principal attached during the handshake (from Spring Security or a custom handshake handler) provides the username key.
Sending with @SendToUser
In a controller method you annotate with @SendToUser. The return value is delivered only to the user who sent the triggering message.
@MessageMapping("/private")
@SendToUser("/queue/reply")
public Note handle(Note in, Principal principal) {
return new Note("Hi " + principal.getName());
}The Client Subscription
The client subscribes to the /user-prefixed destination. Spring resolves it to that client's private queue automatically.
stompClient.subscribe('/user/queue/reply', (msg) => {
console.log('Private:', JSON.parse(msg.body));
});Pushing from Anywhere with the Template
Outside a controller (e.g. from a service or scheduled job) use SimpMessagingTemplate.convertAndSendToUser to reach a specific user by name.
messagingTemplate.convertAndSendToUser(
"alice", "/queue/notifications", new Alert("Payment received"));How Resolution Works
The UserDestinationMessageHandler maps /user/{username}/queue/x to the actual session-specific destination. You address users by name; Spring finds their active sessions.
Multiple Sessions per User
One user may be connected from a phone and a laptop. convertAndSendToUser delivers to all of that user's active sessions, so notifications appear everywhere they are logged in.
Targeting a Single Session
To reach just one device, pass headers selecting a specific simpSessionId rather than broadcasting to every session of the user.
SimpMessageHeaderAccessor h = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE);
h.setSessionId(sessionId);
h.setLeaveMutable(true);
messagingTemplate.convertAndSendToUser(user, "/queue/reply", body, h.getMessageHeaders());User Destinations Across a Cluster
With a single server the simple broker resolves user destinations in-memory. Across multiple nodes you need an external broker (RabbitMQ) plus a UserRegistry broadcast so a node can route to a user connected elsewhere.
Security Note
Never let a client choose another user's destination. Always derive the target from the authenticated Principal, not from client-supplied data, to prevent message hijacking.
Quick Check
Test your knowledge of per-user messaging.
Recap
You delivered private messages:
- The
/userprefix maps to per-session queues @SendToUserreplies to the originating userconvertAndSendToUserpushes to a named user from anywhere- Multiple sessions per user are reached together; target one with session headers
- Always derive the target from the authenticated
Principal
Preguntas frecuentes
¿La lección «Mensajería dirigida a usuarios específicos» es gratis?
Sí — el texto completo de «Mensajería dirigida a usuarios específicos» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de WebSockets & Real-Time Systems with Spring, actualiza a CoddyKit PRO. El curso de WebSockets & Real-Time Systems with Spring incluye 4 lecciones en total.
¿Qué aprenderé en «Mensajería dirigida a usuarios específicos»?
Envíe mensajes privados por usuario mediante STOMP usando destinos de usuario, @SendToUser y SimpMessagingTemplate.convertAndSendToUser. Practicas WebSockets & Real-Time Systems with Spring con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar WebSockets & Real-Time Systems with Spring?
No se requiere experiencia previa. WebSockets & Real-Time Systems with Spring en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.
¿Cuánto tiempo toma la lección «Mensajería dirigida a usuarios específicos»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de WebSockets & Real-Time Systems with Spring?
Sí. Cada lección de WebSockets & Real-Time Systems with Spring incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Interceptores de WebSocket
- Personalización de convertidores de mensajes
- Gestión de sesiones de usuario
- Mensajería dirigida a usuarios específicos