Files
nahodka-back/src/main/java/com/krylov/refound/config/ClusterMessaging.java
SlimusMinus a696a21a1f Run safely with several instances: ShedLock jobs, Redis WebSocket fan-out
- Scheduled jobs (nightly cleanup, moderation, search dictionary rebuild) take
  a ShedLock lock in Redis, so only one instance runs each; the moderation run
  stops before its lock can expire.
- STOMP events (chat messages, unread counters, transcoding status) are
  published to the Redis channel ws:broadcast and every instance hands them to
  its local simple broker, so subscribers on other instances receive them.
  Falls back to local delivery if Redis is down; app.websocket.cluster-broadcast
  switches it off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 01:31:12 +03:00

83 lines
3.8 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.krylov.refound.config;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.nio.charset.StandardCharsets;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Component;
/**
* Рассылка STOMP-сообщений во все экземпляры приложения.
*
* <p>WebSocket-брокер (simple broker) живёт в памяти процесса: подписчики,
* подключённые к другому экземпляру, сообщение не получили бы. Поэтому событие
* публикуется в канал Redis {@value #CHANNEL}, каждый экземпляр (включая
* отправителя) получает его и отдаёт своему локальному брокеру — а тот своим
* подписчикам. Права на подписку по-прежнему проверяет WsStompInterceptor в
* том экземпляре, где подключён клиент.
*
* <p>Если Redis недоступен, сообщение доставляется хотя бы локально.
* Включается свойством {@code app.websocket.cluster-broadcast} (по умолчанию да).
*/
@Slf4j
@Component
public class ClusterMessaging implements MessageListener {
public static final String CHANNEL = "ws:broadcast";
private final SimpMessagingTemplate messagingTemplate;
private final StringRedisTemplate redisTemplate;
private final ObjectMapper objectMapper;
private final boolean clusterBroadcast;
public ClusterMessaging(SimpMessagingTemplate messagingTemplate, StringRedisTemplate redisTemplate,
ObjectMapper objectMapper, @Value("${app.websocket.cluster-broadcast:true}") boolean clusterBroadcast) {
this.messagingTemplate = messagingTemplate;
this.redisTemplate = redisTemplate;
this.objectMapper = objectMapper;
this.clusterBroadcast = clusterBroadcast;
}
record Envelope(String destination, JsonNode payload) {
}
/** Отправляет сообщение подписчикам destination во всех экземплярах. */
public void convertAndSend(String destination, Object payload) {
if (!clusterBroadcast) {
messagingTemplate.convertAndSend(destination, payload);
return;
}
try {
String json = objectMapper.writeValueAsString(new Envelope(destination, objectMapper.valueToTree(payload)));
redisTemplate.convertAndSend(CHANNEL, json);
} catch (Exception e) {
log.warn("Не удалось опубликовать WS-сообщение в Redis ({}), доставляем локально: {}",
destination, e.getMessage());
messagingTemplate.convertAndSend(destination, payload);
}
}
/** Сообщение из канала Redis — от этого или другого экземпляра. */
@Override
public void onMessage(Message message, byte[] pattern) {
try {
Envelope envelope = objectMapper.readValue(new String(message.getBody(), StandardCharsets.UTF_8), Envelope.class);
if (envelope.destination() == null) {
return;
}
messagingTemplate.convertAndSend(envelope.destination(), envelope.payload());
} catch (Exception e) {
log.warn("Некорректное WS-сообщение из Redis: {}", e.getMessage());
}
}
public boolean isClusterBroadcast() {
return clusterBroadcast;
}
}