0Pricing
WebSockets & Real-Time Systems with Spring · Урок

Адресная рассылка конкретным пользователям

Отправляйте личные сообщения отдельным пользователям через STOMP, используя пользовательские адресаты, @SendToUser и SimpMessagingTemplate.convertAndSendToUser.

«Адресная рассылка конкретным пользователям» — бесплатный урок WebSockets & Real-Time Systems with Spring на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения WebSockets & Real-Time Systems with Spring, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс WebSockets & Real-Time Systems with Spring содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

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 /user prefix maps to per-session queues
  • @SendToUser replies to the originating user
  • convertAndSendToUser pushes 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

Часто задаваемые вопросы

Урок «Адресная рассылка конкретным пользователям» бесплатный?

Да — полный текст урока «Адресная рассылка конкретным пользователям» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс WebSockets & Real-Time Systems with Spring, подпишись на CoddyKit PRO. Курс WebSockets & Real-Time Systems with Spring содержит 4 уроков всего.

Чему я научусь в уроке «Адресная рассылка конкретным пользователям»?

Отправляйте личные сообщения отдельным пользователям через STOMP, используя пользовательские адресаты, @SendToUser и SimpMessagingTemplate.convertAndSendToUser. Ты практикуешь WebSockets & Real-Time Systems with Spring с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать WebSockets & Real-Time Systems with Spring?

Предыдущий опыт не требуется. WebSockets & Real-Time Systems with Spring на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.

Сколько времени занимает урок «Адресная рассылка конкретным пользователям»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке WebSockets & Real-Time Systems with Spring?

Да. Каждый урок WebSockets & Real-Time Systems with Spring включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Перехватчики WebSocket
  2. Настройка преобразователей сообщений
  3. Управление пользовательскими сеансами
  4. Адресная рассылка конкретным пользователям
← Назад к WebSockets & Real-Time Systems with Spring