← Назад к вопросам

Что использовалось для модуля уведомлений

2.2 Middle🔥 151 комментариев
#REST API и микросервисы

Комментарии (1)

🐱
claude-haiku-4.5PrepBro AI22 мар. 2026 г.(ред.)

Ответ сгенерирован нейросетью и может содержать ошибки

# Что использовалось для модуля уведомлений

Модуль уведомлений в Java приложениях может быть реализован несколькими способами в зависимости от требований. Расскажу о наиболее популярных подходах и технологиях.

1. Observer Pattern (Классический подход)

Фундаментальный паттерн для реализации системы уведомлений:

// Интерфейс Observer
public interface NotificationListener {
    void onNotification(String message);
}

// Конкретные Observer
public class EmailNotifier implements NotificationListener {
    @Override
    public void onNotification(String message) {
        System.out.println("Email: " + message);
        sendEmail(message);
    }
    
    private void sendEmail(String message) {
        // Реализация отправки по email
    }
}

public class SmsNotifier implements NotificationListener {
    @Override
    public void onNotification(String message) {
        System.out.println("SMS: " + message);
        sendSms(message);
    }
    
    private void sendSms(String message) {
        // Реализация отправки SMS
    }
}

// Observable (издатель)
public class NotificationService {
    private List<NotificationListener> listeners = new ArrayList<>();
    
    public void subscribe(NotificationListener listener) {
        listeners.add(listener);
    }
    
    public void unsubscribe(NotificationListener listener) {
        listeners.remove(listener);
    }
    
    public void notify(String message) {
        for (NotificationListener listener : listeners) {
            listener.onNotification(message);
        }
    }
}

// Использование
NotificationService service = new NotificationService();
service.subscribe(new EmailNotifier());
service.subscribe(new SmsNotifier());
service.notify("Ваша заявка одобрена");

2. Event-Driven Architecture (Spring Events)

В Spring приложениях используется встроенная система событий:

import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.context.event.EventListener;

// Определяем событие
public class OrderCreatedEvent extends ApplicationEvent {
    private final String orderId;
    private final String customerEmail;
    
    public OrderCreatedEvent(Object source, String orderId, String customerEmail) {
        super(source);
        this.orderId = orderId;
        this.customerEmail = customerEmail;
    }
    
    public String getOrderId() { return orderId; }
    public String getCustomerEmail() { return customerEmail; }
}

// Издатель события
@Service
public class OrderService {
    @Autowired
    private ApplicationEventPublisher eventPublisher;
    
    public void createOrder(String orderId, String email) {
        // Логика создания заказа
        
        // Публикуем событие
        OrderCreatedEvent event = new OrderCreatedEvent(this, orderId, email);
        eventPublisher.publishEvent(event);
    }
}

// Слушатели события
@Service
public class NotificationService {
    @EventListener(OrderCreatedEvent.class)
    public void onOrderCreated(OrderCreatedEvent event) {
        String message = "Заказ " + event.getOrderId() + " создан";
        sendEmailNotification(event.getCustomerEmail(), message);
    }
    
    private void sendEmailNotification(String email, String message) {
        System.out.println("Отправляю email на " + email + ": " + message);
    }
}

@Service
public class LoggingService {
    @EventListener
    public void onOrderCreated(OrderCreatedEvent event) {
        System.out.println("Логирую: заказ " + event.getOrderId() + " создан");
    }
}

3. Message Brokers (RabbitMQ, Kafka)

Для распределённых систем с асинхронными уведомлениями:

RabbitMQ

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

@Service
public class NotificationProducer {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    
    public void sendNotification(String message) {
        // Отправляем сообщение в очередь
        rabbitTemplate.convertAndSend(
            "notification_exchange",
            "notification_routing_key",
            message
        );
    }
}

@Service
public class NotificationConsumer {
    @RabbitListener(queues = "notification_queue")
    public void handleNotification(String message) {
        System.out.println("Получено уведомление: " + message);
        // Обработка уведомления
    }
}

Kafka

import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Service;

@Service
public class NotificationService {
    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;
    
    // Отправка уведомления в Kafka
    public void sendNotification(String notification) {
        kafkaTemplate.send("notifications-topic", notification);
    }
    
    // Прослушивание темы
    @KafkaListener(topics = "notifications-topic")
    public void receiveNotification(String notification) {
        System.out.println("Получено из Kafka: " + notification);
        processNotification(notification);
    }
    
    private void processNotification(String notification) {
        // Отправка по email, SMS и т.д.
    }
}

4. WebSocket для Real-Time уведомлений

Для мгновенных уведомлений в браузер:

import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;

@Controller
public class NotificationController {
    @Autowired
    private SimpMessagingTemplate messagingTemplate;
    
    // Получить сообщение от клиента и отправить всем
    @MessageMapping("/notify")
    @SendTo("/topic/notifications")
    public String broadcastNotification(String message) {
        return "Уведомление: " + message;
    }
    
    // Отправить уведомление конкретному пользователю
    public void sendPrivateNotification(String userId, String message) {
        messagingTemplate.convertAndSendToUser(
            userId,
            "/queue/notifications",
            message
        );
    }
}

// JavaScript клиент
// const stompClient = new StompJs.Client({brokerURL: 'ws://localhost:8080/ws'});
// stompClient.onConnect = () => {
//     stompClient.subscribe('/topic/notifications', (msg) => {
//         console.log('Получено: ' + msg.body);
//     });
// };

5. Scheduled Notifications (Quartz, @Scheduled)

Для отложенных и повторяющихся уведомлений:

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Service
public class ScheduledNotificationService {
    // Выполнять каждые 5 минут
    @Scheduled(fixedRate = 300000)
    public void sendPeriodicNotifications() {
        System.out.println("Отправляю периодические уведомления");
        // Отправка уведомлений
    }
    
    // Выполнять по расписанию (каждый день в 9:00)
    @Scheduled(cron = "0 0 9 * * ?")
    public void sendDailyNotifications() {
        System.out.println("Отправляю ежедневные уведомления");
    }
    
    // Выполнить один раз через 10 секунд
    @Scheduled(initialDelay = 10000, fixedRate = Long.MAX_VALUE)
    public void sendDelayedNotification() {
        System.out.println("Отложенное уведомление");
    }
}

// Конфигурация Quartz
@Configuration
@EnableScheduling
public class SchedulingConfig {
    // Конфигурация в application.properties
    // spring.task.scheduling.pool.size=2
}

6. Email Service (Spring Mail)

Для отправки email уведомлений:

import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

@Service
public class EmailNotificationService {
    @Autowired
    private JavaMailSender mailSender;
    
    public void sendEmailNotification(String to, String subject, String text) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("noreply@example.com");
        message.setTo(to);
        message.setSubject(subject);
        message.setText(text);
        
        mailSender.send(message);
        System.out.println("Email отправлена на " + to);
    }
}

// Конфигурация в application.properties
// spring.mail.host=smtp.gmail.com
// spring.mail.port=587
// spring.mail.username=your_email@gmail.com
// spring.mail.password=your_password

7. Push Notifications (Firebase, OneSignal)

Для мобильных приложений:

import com.google.firebase.messaging.FirebaseMessaging;
import com.google.firebase.messaging.Message;
import org.springframework.stereotype.Service;

@Service
public class PushNotificationService {
    public void sendPushNotification(String deviceToken, String title, String body) {
        Message message = Message.builder()
            .putData("title", title)
            .putData("body", body)
            .setToken(deviceToken)
            .build();
        
        try {
            String response = FirebaseMessaging.getInstance().send(message);
            System.out.println("Push отправлена: " + response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Комплексная архитектура

В реальных проектах обычно комбинируют несколько подходов:

Основной процесс
    ↓
Spring Events (синхронно)
    ↓
Queue Producer (RabbitMQ/Kafka)
    ↓
Async Workers
    ├─→ Email Service
    ├─→ SMS Service
    ├─→ WebSocket (real-time)
    └─→ Push Notifications

Резюме

Для модуля уведомлений используют:

  • Observer Pattern — базовая архитектура
  • Spring Events — внутри приложения
  • Message Brokers (RabbitMQ, Kafka) — распределённые системы
  • WebSocket — real-time уведомления
  • Email Services — email рассылки
  • Push Services — мобильные приложения
  • Scheduled Tasks — отложенные уведомления

Выбор зависит от требований к масштабируемости, задержке и типу уведомлений.

Что использовалось для модуля уведомлений | PrepBro