실시간 데이터 푸시 아키텍처
연결된 클라이언트에 데이터 스트림과 업데이트를 지속적으로 푸시하는 아키텍처를 설계합니다.
실시간 데이터 푸시 아키텍처은(는) CoddyKit의 무료 WebSockets & Real-Time Systems with Spring 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 WebSockets & Real-Time Systems with Spring 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. WebSockets & Real-Time Systems with Spring 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Real-Time Data Push
Modern applications thrive on instant updates. Imagine a stock ticker, a sports score app, or a chat room – all need data delivered as it happens, not on request.
This lesson explores how to design server-side architectures that actively push continuous data streams and updates to connected clients.
Publisher-Subscriber Model
At the core of data push is the Publisher-Subscriber (Pub/Sub) pattern. Here's how it works:
- Publishers: These are server-side components that generate and send messages.
- Subscribers: These are connected clients (e.g., web browsers, mobile apps) that express interest in specific types of messages.
The system delivers messages from publishers to all interested subscribers, decoupling the data source from its consumers.
Server-Side Data Sources
Where does the data you want to push originate? Common sources include:
- Database Changes: Real-time updates when data in your database is modified.
- External APIs: Events or data received from third-party services.
- Internal Application Events: Actions within your own application (e.g., a new order placed, a user status change).
- Message Queues: Data consumed from systems like Kafka or RabbitMQ.
Your push architecture acts as a bridge, taking data from these sources and sending it to clients.
Spring Push Service Example
Let's see a simple Spring Boot service that simulates generating and pushing data to a STOMP topic. We use SimpMessagingTemplate, Spring's helper for sending messages to broker destinations.
Try running this example:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
// Main Spring Boot Application
@SpringBootApplication
@EnableScheduling // Enables scheduled tasks like our data push
@EnableWebSocketMessageBroker // Enables STOMP over WebSockets
public class RealTimeApp {
public static void main(String[] args) {
SpringApplication.run(RealTimeApp.class, args);
}
}
// WebSocket Configuration for STOMP
@Configuration
@EnableWebSocketMessageBroker
class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
// Enable a simple in-memory broker for '/topic' and '/user' destinations
config.enableSimpleBroker("/topic", "/user");
// Prefix for messages from clients to server-side @MessageMapping methods
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
// Register the '/ws' endpoint for WebSocket handshake
registry.addEndpoint("/ws").withSockJS();
}
}
// Service to push real-time data
@Service
class DataPushService {
private final SimpMessagingTemplate messagingTemplate;
private int counter = 0;
public DataPushService(SimpMessagingTemplate messagingTemplate) {
this.messagingTemplate = messagingTemplate;
}
// This method runs every 3 seconds and pushes data
@Scheduled(fixedRate = 3000)
public void pushTimeUpdate() {
String message = "Current time: " + LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")) + " (Update " + (++counter) + ")";
// Push to a public topic. Clients can subscribe to '/topic/updates'.
messagingTemplate.convertAndSend("/topic/updates", message);
System.out.println("Pushed to /topic/updates: " + message);
}
}Broadcasting Updates
The example in the previous scene demonstrates broadcasting. When our DataPushService sends a message to /topic/updates, it's pushed to all clients currently subscribed to that topic.
- This is ideal for public data streams like chat rooms, news feeds, or global notifications.
- It's an efficient fan-out architecture, where a single message from the server reaches multiple clients simultaneously.
Targeted Push: Topics & Users
While topics are great for broadcasting, sometimes you need to send messages to a specific user or a small group. STOMP supports two main types of destinations for pushing data:
- Topics (e.g.,
/topic/news): For broadcasting messages to all subscribers. - User Destinations (e.g.,
/user/{userId}/queue/notifications): For sending private, user-specific messages.
Understanding this distinction is crucial for designing flexible push architectures.
Private User Notifications
To send a private message or notification to a specific user, Spring's SimpMessagingTemplate provides the convertAndSendToUser() method.
This method automatically routes the message to the correct WebSocket session(s) associated with that user ID.
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;
@Service
public class NotificationService {
private final SimpMessagingTemplate messagingTemplate;
public NotificationService(SimpMessagingTemplate messagingTemplate) {
this.messagingTemplate = messagingTemplate;
}
public void sendPrivateNotification(String userId, String message) {
// The client would subscribe to '/user/queue/notifications'
// Spring handles the '/user/{userId}' part automatically.
messagingTemplate.convertAndSendToUser(userId, "/queue/notifications", message);
System.out.println("Sent private notification to " + userId + ": " + message);
}
}External Event Integration
For complex, high-volume, or distributed systems, your data sources might be external message brokers like Apache Kafka or RabbitMQ.
Your push architecture would involve:
- A Spring component acting as a consumer, listening to messages from the external broker.
- Upon receiving a message, this component then uses
SimpMessagingTemplateto push the data via WebSockets to relevant clients.
This pattern ensures loose coupling and scalability.
Scaling Push Architectures
As your application grows, you'll need to scale your data push system:
- Horizontal Scaling: Run multiple instances of your WebSocket server.
- External Message Brokers: Essential for inter-server communication when horizontally scaled. They ensure messages reach all relevant clients, regardless of which server instance they're connected to.
- Load Balancers: Distribute client connections across your server instances. Sticky sessions might be needed for simple setups, or more advanced session management for complex ones.
Architecture Quiz
You're building a real-time application. Users need to receive updates about their own specific orders, while also seeing a public feed of recently placed orders by everyone. Which architectural approach is best for each scenario?
Recap: Data Push Mastery
You've now explored the essential concepts behind real-time data push architectures:
- The Publisher-Subscriber model as a foundation.
- Identifying various server-side data sources.
- Implementing broadcasting via topics and private notifications via user destinations in Spring.
- Understanding the role of external event sources and strategies for scaling your push system.
This knowledge empowers you to design robust and efficient real-time data delivery for any application!
자주 묻는 질문
“실시간 데이터 푸시 아키텍처” 강의는 무료인가요?
네 — “실시간 데이터 푸시 아키텍처” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 WebSockets & Real-Time Systems with Spring 강의 전체를 잠금 해제할 수 있습니다. WebSockets & Real-Time Systems with Spring 강의에는 총 4개의 강의가 포함되어 있습니다.
“실시간 데이터 푸시 아키텍처”에서 뭘 배우나요?
연결된 클라이언트에 데이터 스트림과 업데이트를 지속적으로 푸시하는 아키텍처를 설계합니다. 브라우저에서 직접 실행하는 실습 코드로 WebSockets & Real-Time Systems with Spring을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
WebSockets & Real-Time Systems with Spring을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 WebSockets & Real-Time Systems with Spring은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“실시간 데이터 푸시 아키텍처” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 WebSockets & Real-Time Systems with Spring 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 WebSockets & Real-Time Systems with Spring 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 서버 전송 이벤트(SSE)와 WebSockets 비교
- 실시간 데이터 푸시 아키텍처
- 사용자 알림 구현
- 상태 및 온라인 상태 추적