0Pricing
WebSockets & Real-Time Systems with Spring · Aula

Envio e receção de mensagens STOMP

Implemente produtores e consumidores de mensagens com STOMP, incluindo destinos por tópico e específicos de cada utilizador.

Envio e receção de mensagens STOMP é uma aula grátis de WebSockets & Real-Time Systems with Spring no CoddyKit. Esta é a aula 3 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de WebSockets & Real-Time Systems with Spring, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de WebSockets & Real-Time Systems with Spring inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

Intro to STOMP Messaging

In this lesson, we'll learn how to send messages from a client to our Spring server and how the server can then send messages back, either to a general topic or a specific user.

STOMP provides a clear, structured way to route these real-time messages, making our applications more predictable and easier to manage.

Producers and Consumers

Think of messaging in terms of producers and consumers:

  • Producers send messages (e.g., a chat client sending a message).
  • Consumers receive messages (e.g., another chat client displaying the message).

In a real-time app, clients often act as both!

Sending to Public Topics

A topic is a public destination. When a message is sent to a topic, all clients currently subscribed to that topic will receive the message.

It's like a broadcast channel or a public chat room where everyone hears what's said.

Common topic paths start with /topic/, e.g., /topic/public-chat or /topic/news-feed.

Server: Handling Topic Messages

On the Spring server, we use @MessageMapping to handle incoming messages from clients to a specific destination. We can then use SimpMessagingTemplate to send messages back out to a topic.

This snippet shows a server method receiving a message and then broadcasting it to a topic.

@Controller
public class ChatController {

  @Autowired
  private SimpMessagingTemplate messagingTemplate;

  @MessageMapping("/chat.sendMessage")
  public void sendMessage(@Payload String chatMessage) {
    // Client sends to /app/chat.sendMessage
    // Server broadcasts to /topic/public-chat
    messagingTemplate.convertAndSend(
        "/topic/public-chat", "New message: " + chatMessage);
  }
}

Client: Subscribing to Topics

On the client-side (e.g., JavaScript), you subscribe to a topic to receive messages. When the server sends a message to /topic/public-chat, all subscribed clients get it.

A client might subscribe like this:

stompClient.subscribe('/topic/public-chat', function(message) { // Handle received message });

User-Specific Messaging

Sometimes you need to send a message directly to a single, specific user, not a public topic. This is called user-specific messaging.

It's perfect for:

  • Private chat messages
  • Personal notifications
  • Direct alerts

STOMP and Spring handle the routing automatically for you.

Server: Sending to a User

Spring's SimpMessagingTemplate has a special method, convertAndSendToUser, to target messages to a specific user. You provide the username and the specific destination within that user's queue.

The framework translates /user/{username}/queue/messages into a unique queue for that user.

@Controller
public class UserController {

  @Autowired
  private SimpMessagingTemplate messagingTemplate;

  @MessageMapping("/private.send")
  public void sendPrivateMessage(
      @Payload String privateMessage, Principal principal) {
    // principal.getName() gets the current user's username
    String recipient = "someOtherUser"; // This would come from payload

    messagingTemplate.convertAndSendToUser(
        recipient, "/queue/private-messages", 
        "From " + principal.getName() + ": " + privateMessage);
  }
}

Client: Subscribing to User Queue

A client subscribes to their own user-specific queue to receive private messages. The path usually looks like /user/queue/private-messages.

The key here is that the /user prefix is special. The STOMP broker automatically routes messages sent to a particular user to their unique session-specific queue.

Message Payloads

Messages sent over STOMP usually carry data in their payload (the message body). The most common format for this data is JSON.

Spring's STOMP support automatically converts Java objects to JSON (and vice-versa) when you use @Payload and convertAndSend methods, making it super easy to work with structured data.

Quick Check: STOMP Destinations

You want to send a personal notification to only one specific user. Which type of STOMP destination should you use?

Recap: Sending & Receiving

We've explored how to send and receive STOMP messages in Spring applications:

  • Topics (e.g., /topic/public-chat) are for broadcasting messages to all subscribed clients.
  • User-specific destinations (e.g., /user/queue/private-messages) are for sending private messages to a single user.
  • Spring's SimpMessagingTemplate and @MessageMapping annotations simplify both sending and receiving.

You can now build interactive features like chat rooms and private notifications!

Perguntas Frequentes

A aula “Envio e receção de mensagens STOMP” é grátis?

Sim — o texto completo de “Envio e receção de mensagens STOMP” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de WebSockets & Real-Time Systems with Spring, atualize para CoddyKit PRO. O curso de WebSockets & Real-Time Systems with Spring inclui 4 aulas no total.

O que vou aprender em “Envio e receção de mensagens STOMP”?

Implemente produtores e consumidores de mensagens com STOMP, incluindo destinos por tópico e específicos de cada utilizador. Você pratica WebSockets & Real-Time Systems with Spring com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar WebSockets & Real-Time Systems with Spring?

Nenhuma experiência prévia é necessária. WebSockets & Real-Time Systems with Spring no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 3 de 4.

Quanto tempo leva a aula “Envio e receção de mensagens STOMP”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de WebSockets & Real-Time Systems with Spring?

Sim. Cada aula de WebSockets & Real-Time Systems with Spring inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Introdução ao protocolo STOMP
  2. Configuração do STOMP com Spring
  3. Envio e receção de mensagens STOMP
  4. Proteção de endpoints STOMP com Spring Security
← Voltar para WebSockets & Real-Time Systems with Spring