Messaggistica mirata per utenti specifici
Invii messaggi privati e destinati a singoli utenti tramite STOMP usando user destinations, @SendToUser e SimpMessagingTemplate.convertAndSendToUser.
Messaggistica mirata per utenti specifici è una lezione WebSockets & Real-Time Systems with Spring gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento WebSockets & Real-Time Systems with Spring, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso WebSockets & Real-Time Systems with Spring include 4 lezioni in totale.
Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.
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
Impara WebSockets & Real-Time Systems with Spring con un tutor IA — gratis
Scrivi ed esegui vero codice nel tuo browser, ricevi aiuto istantaneo da un tutor IA disponibile 24/7, e riprendi da dove hai lasciato sul web o nell'app.
- Corsi
- 12
- Lezioni
- 48
Domande Frequenti
La lezione «Messaggistica mirata per utenti specifici» è gratuita?
Sì — il testo completo di «Messaggistica mirata per utenti specifici» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso WebSockets & Real-Time Systems with Spring, passa a CoddyKit PRO. Il corso WebSockets & Real-Time Systems with Spring include 4 lezioni in totale.
Cosa imparerò in «Messaggistica mirata per utenti specifici»?
Invii messaggi privati e destinati a singoli utenti tramite STOMP usando user destinations, @SendToUser e SimpMessagingTemplate.convertAndSendToUser. Eserciti WebSockets & Real-Time Systems with Spring con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.
Ho bisogno di esperienza per iniziare WebSockets & Real-Time Systems with Spring?
Non è richiesta alcuna esperienza precedente. WebSockets & Real-Time Systems with Spring su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.
Quanto tempo richiede la lezione «Messaggistica mirata per utenti specifici»?
La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.
Posso scrivere ed eseguire codice in questa lezione WebSockets & Real-Time Systems with Spring?
Sì. Ogni lezione WebSockets & Real-Time Systems with Spring include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.
Tutte le lezioni di questo corso
- Interceptor WebSocket
- Personalizzazione dei converter dei messaggi
- Gestione delle sessioni utente
- Messaggistica mirata per utenti specifici