Pesan Terarah kepada Pengguna Tertentu
Kirim pesan pribadi per pengguna melalui STOMP menggunakan tujuan pengguna, @SendToUser, dan SimpMessagingTemplate.convertAndSendToUser.
Pesan Terarah kepada Pengguna Tertentu adalah pelajaran WebSockets & Real-Time Systems with Spring gratis di CoddyKit. Ini adalah pelajaran 4 dari 4. Kamu bisa membaca pelajaran lengkapnya di bawah secara gratis — lalu praktikkan langsung di browser dengan editor kode bawaan dan tutor AI 24/7. Ini adalah bagian dari jalur belajar WebSockets & Real-Time Systems with Spring, dan progresmu tersinkronisasi di web dan aplikasi CoddyKit. Kursus WebSockets & Real-Time Systems with Spring mencakup 4 pelajaran total.
Bagian dari pelajaran ini belum diterjemahkan dan ditampilkan dalam bahasa Inggris.
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
Pertanyaan yang Sering Diajukan
Apakah pelajaran “Pesan Terarah kepada Pengguna Tertentu” gratis?
Ya — teks lengkap “Pesan Terarah kepada Pengguna Tertentu” gratis dibaca di sini di web. Untuk praktiknya secara interaktif (editor kode bawaan dan tutor AI 24/7) dan buka sisa kursus WebSockets & Real-Time Systems with Spring, upgrade ke CoddyKit PRO. Kursus WebSockets & Real-Time Systems with Spring mencakup 4 pelajaran total.
Apa yang akan aku pelajari di “Pesan Terarah kepada Pengguna Tertentu”?
Kirim pesan pribadi per pengguna melalui STOMP menggunakan tujuan pengguna, @SendToUser, dan SimpMessagingTemplate.convertAndSendToUser. Kamu berlatih WebSockets & Real-Time Systems with Spring dengan kode praktik yang langsung kamu jalankan di browser, dan tutor AI 24/7 menjawab pertanyaanmu saat kamu mengerjakan pelajaran ini.
Apakah aku perlu pengalaman untuk memulai WebSockets & Real-Time Systems with Spring?
Tidak diperlukan pengalaman sebelumnya. WebSockets & Real-Time Systems with Spring di CoddyKit dirancang untuk pemula hingga pelajar tingkat lanjut, jadi kamu bisa memulai di sini atau dari awal dan belajar sesuai kecepatan kamu sendiri. Ini adalah pelajaran 4 dari 4.
Berapa lama pelajaran “Pesan Terarah kepada Pengguna Tertentu” memakan waktu?
Sebagian besar pelajaran CoddyKit memakan waktu sekitar 5–10 menit. Setiap pelajaran ringkas dan interaktif, jadi kamu membuat kemajuan stabil dan melanjutkan dari tempat kamu tinggalkan di web dan aplikasi.
Bisakah aku menulis dan menjalankan kode dalam pelajaran WebSockets & Real-Time Systems with Spring ini?
Ya. Setiap pelajaran WebSockets & Real-Time Systems with Spring menyertakan editor kode bawaan, jadi kamu menulis dan menjalankan kode nyata langsung di browser dan mendapatkan umpan balik AI instan — tidak diperlukan penyiapan lokal.
Semua pelajaran dalam kursus ini
- Pencegat WebSocket
- Kustomisasi Pengonversi Pesan
- Pengelolaan Sesi Pengguna
- Pesan Terarah kepada Pengguna Tertentu