WebSockets & Real-Time Systems with Spring · 课时

向特定用户定向发送消息

使用用户目标地址、@SendToUser 和 SimpMessagingTemplate.convertAndSendToUser,通过 STOMP 发送私有的、面向单个用户的消息。

第 4 / 4 课13 个步骤

向特定用户定向发送消息 是 CoddyKit 上的免费 WebSockets & Real-Time Systems with Spring 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 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
免费开始

用 AI 导师学习 WebSockets & Real-Time Systems with Spring — 免费

在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。

课程
12
课程
48

常见问题解答

「向特定用户定向发送消息」课时是免费的吗?

是的 — 「向特定用户定向发送消息」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 WebSockets & Real-Time Systems with Spring 课程的其余内容,请升级到 CoddyKit PRO。 WebSockets & Real-Time Systems with Spring 课程共包含 4 节课。

「向特定用户定向发送消息」这节课中我会学到什么?

使用用户目标地址、@SendToUser 和 SimpMessagingTemplate.convertAndSendToUser,通过 STOMP 发送私有的、面向单个用户的消息。 你通过在浏览器中直接运行的动手代码来练习 WebSockets & Real-Time Systems with Spring,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 WebSockets & Real-Time Systems with Spring 需要有经验吗?

无需任何先前经验。CoddyKit 上的 WebSockets & Real-Time Systems with Spring 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 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