0Pricing
WebSockets & Real-Time Systems with Spring · درس

تنفيذ إشعارات المستخدمين

ابنوا نظام إشعارات قويًا لإيصال التنبيهات والتحديثات الفورية إلى المستخدمين في الوقت الحقيقي.

تنفيذ إشعارات المستخدمين درس مجاني في WebSockets & Real-Time Systems with Spring على CoddyKit. هذا هو الدرس 3 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في WebSockets & Real-Time Systems with Spring، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة WebSockets & Real-Time Systems with Spring 4 دروس في المجموع.

بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.

What are User Notifications?

User notifications are essential for modern applications. They keep users informed about important events, updates, or messages in real-time.

Think about social media alerts, new email warnings, or game invites. They boost engagement and ensure users don't miss crucial information.

Core Notification System

A robust real-time notification system typically involves a few key components:

  • Backend Service: To generate and send notifications.
  • Message Broker: To route notifications efficiently to the correct users.
  • Client-Side Logic: To receive, display, and manage notifications.

We'll focus on the in-app, real-time aspect using Spring WebSockets and STOMP.

Crafting a Notification Model

First, we need a data structure for our notifications. This model defines what information each notification carries.

Key fields often include:

  • id: Unique identifier.
  • recipientId: Who gets the notification.
  • senderId: Who sent it (optional).
  • message: The actual content.
  • type: Category (e.g., "message", "alert", "friend_request").
  • timestamp: When it was created.
  • isRead: Has the user seen it? (true/false)

Server-Side Notification Creation

On the server, an event (like a new message or a user action) triggers the creation of a Notification object. This object is then processed and sent.

Here's a simple Java class representing our notification model:

public class Notification {
  private String id;
  private String recipientId;
  private String senderId;
  private String message;
  private String type;
  private long timestamp;
  private boolean isRead;

  // Constructor
  public Notification(String recipientId, String senderId, String message, String type) {
    this.id = java.util.UUID.randomUUID().toString();
    this.recipientId = recipientId;
    this.senderId = senderId;
    this.message = message;
    this.type = type;
    this.timestamp = System.currentTimeMillis();
    this.isRead = false;
  }

  // Getters (and setters if needed)
  public String getId() { return id; }
  public String getRecipientId() { return recipientId; }
  public String getSenderId() { return senderId; }
  public String getMessage() { return message; }
  public String getType() { return type; }
  public long getTimestamp() { return timestamp; }
  public boolean isRead() { return isRead; }
  public void setRead(boolean read) { isRead = read; }

  @Override
  public String toString() {
    return "Notification [recipient=" + recipientId + ", msg='" + message + "']";
  }
}

Directing User Notifications

To send a notification to a specific user, we leverage STOMP's user destinations. Spring's messaging template simplifies this.

The destination typically looks like /user/{userId}/queue/notifications. When the server sends a message to this destination, Spring automatically routes it to the WebSocket session(s) associated with that userId.

This ensures only the intended recipient receives the notification.

Pushing Notifications (Server Concept)

On the server, when an event triggers a notification, a backend service will create a Notification object. Then, using Spring's SimpMessagingTemplate, it sends this notification to the recipient's private STOMP queue.

The convertAndSendToUser method is crucial here, mapping the user ID to their active WebSocket session(s).

While SimpMessagingTemplate needs a Spring context, we can illustrate the notification object and a conceptual send:

public class Notification {
  private String recipientId;
  private String message;
  private long timestamp;

  public Notification(String recipientId, String message) {
    this.recipientId = recipientId;
    this.message = message;
    this.timestamp = System.currentTimeMillis();
  }

  public String getRecipientId() { return recipientId; }
  public String getMessage() { return message; }
  public long getTimestamp() { return timestamp; }

  @Override
  public String toString() {
    return "Notification [to=" + recipientId + ", msg='" + message + "']";
  }

  public static void main(String[] args) {
    // This simulates creating and conceptually sending a notification
    String userId = "user123";
    String notificationMessage = "You have a new message!";
    Notification newNotification = new Notification(userId, notificationMessage);

    System.out.println("Created notification: " + newNotification);
    System.out.println("Spring's SimpMessagingTemplate would then send this to /user/" + userId + "/queue/notifications");
    System.out.println("Client-side would receive this via their WebSocket subscription.");
  }
}

Client Listens for Updates

On the client side (e.g., a web browser), the user needs to subscribe to their personal notification queue. This is done via the WebSocket connection, once authenticated.

The subscription destination will match the server-side sending pattern: /user/queue/notifications.

Any message sent by the server to this destination for the authenticated user will be received by the client.

Client-Side Subscription (JS)

Here's a basic JavaScript snippet using a STOMP client library (like stomp.js or @stomp/stompjs) to connect and subscribe.

// Assume 'stompClient' is already connected to WebSocket
// and authenticated.

// Function to handle incoming notifications
function onNotificationReceived(notification) {
  console.log("Received notification:", notification.body);
  // Parse JSON body, e.g., JSON.parse(notification.body)
  // Then update UI to display the notification
  displayNotification(JSON.parse(notification.body));
}

// Function to display notification in UI
function displayNotification(notifObj) {
    const notifArea = document.getElementById("notificationArea");
    const newNotif = document.createElement("div");
    newNotif.innerHTML = `<b>${notifObj.message}</b> 
                              <small>(${new Date(notifObj.timestamp).toLocaleTimeString()})</small>`;
    notifArea.prepend(newNotif);
}

// Subscribe to the user's private notification queue
stompClient.subscribe('/user/queue/notifications', onNotificationReceived);

console.log("Subscribed to /user/queue/notifications");
// In a real app, you'd have a 'connect' function first.
// Example: stompClient.connect({}, frame => { ... subscribe here ... });

Marking Notifications as Read

Once a user views a notification, it's good practice to mark it as read. This typically involves a separate interaction, not directly through WebSockets for the update itself.

The client can send a simple REST API call (e.g., a PUT or POST request) to the backend, indicating which notification(s) should be marked as read.

The backend then updates the notification's isRead status in the database.

Notification Delivery Check

You've built a system to send real-time notifications to specific users. How does the server ensure a notification reaches only the intended recipient?

Recap: Building Notifiers

In this lesson, we explored how to implement a real-time user notification system.

  • We designed a Notification model.
  • Learned to use Spring's SimpMessagingTemplate with convertAndSendToUser for targeted delivery.
  • Understood how clients subscribe to their private queues (/user/queue/notifications).
  • Discussed marking notifications as read via a REST API.

These principles allow you to build engaging, interactive applications that keep users informed instantly!

الأسئلة الشائعة

هل درس «تنفيذ إشعارات المستخدمين» مجاني؟

نعم — نص درس «تنفيذ إشعارات المستخدمين» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة WebSockets & Real-Time Systems with Spring، انتقل إلى CoddyKit PRO. تتضمن دورة WebSockets & Real-Time Systems with Spring 4 دروس في المجموع.

ماذا ستتعلم في «تنفيذ إشعارات المستخدمين»؟

ابنوا نظام إشعارات قويًا لإيصال التنبيهات والتحديثات الفورية إلى المستخدمين في الوقت الحقيقي. تتمرن على WebSockets & Real-Time Systems with Spring مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ WebSockets & Real-Time Systems with Spring؟

لا تُشترط خبرة سابقة. WebSockets & Real-Time Systems with Spring على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 3 من أصل 4.

كم من الوقت يستغرق درس «تنفيذ إشعارات المستخدمين»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس WebSockets & Real-Time Systems with Spring هذا؟

نعم. كل درس في WebSockets & Real-Time Systems with Spring يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. الأحداث المرسلة من الخادم (SSE) مقابل WebSockets
  2. بنيات دفع البيانات الفورية
  3. تنفيذ إشعارات المستخدمين
  4. تتبع الحضور وحالة الاتصال
← العودة إلى WebSockets & Real-Time Systems with Spring