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>
This commit is contained in:
SlimusMinus
2026-10-20 01:31:12 +03:00
parent 83270a8ece
commit a696a21a1f
11 changed files with 246 additions and 13 deletions

View File

@@ -0,0 +1,82 @@
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;
}
}

View File

@@ -5,10 +5,13 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.krylov.refound.dto.CachedPostPage;
import com.krylov.refound.dto.MapMarkerDto;
import java.util.List;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@@ -54,4 +57,15 @@ public class RedisConfig {
template.setValueSerializer(valueSerializer);
return template;
}
}
/** Подписка на канал рассылки WebSocket-сообщений между экземплярами (см. ClusterMessaging). */
@Bean
@ConditionalOnProperty(name = "app.websocket.cluster-broadcast", havingValue = "true", matchIfMissing = true)
public RedisMessageListenerContainer wsBroadcastListenerContainer(RedisConnectionFactory connectionFactory,
ClusterMessaging clusterMessaging) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.addMessageListener(clusterMessaging, new ChannelTopic(ClusterMessaging.CHANNEL));
return container;
}
}

View File

@@ -0,0 +1,30 @@
package com.krylov.refound.config;
import net.javacrumbs.shedlock.core.LockProvider;
import net.javacrumbs.shedlock.provider.redis.spring.RedisLockProvider;
import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
/**
* Распределённая блокировка фоновых задач (ShedLock). Приложение может работать
* в нескольких экземплярах: без блокировки ночная чистка и модерация запускались
* бы в каждом из них одновременно. Задача с {@code @SchedulerLock} выполняется
* тем экземпляром, который первым взял блокировку в Redis
* ({@code job-lock:refound:<имя задачи>}); остальные пропускают запуск.
*
* <p>Если Redis недоступен, блокировку взять нельзя и задача пропускается до
* следующего запуска — это безопаснее, чем выполнить её во всех экземплярах.
*/
@Configuration
@EnableSchedulerLock(defaultLockAtMostFor = "PT10M")
public class SchedulerLockConfig {
static final String LOCK_ENVIRONMENT = "refound";
@Bean
public LockProvider lockProvider(RedisConnectionFactory connectionFactory) {
return new RedisLockProvider(connectionFactory, LOCK_ENVIRONMENT);
}
}