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:
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import java.util.concurrent.atomic.LongAdder;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import net.javacrumbs.shedlock.spring.annotation.SchedulerLock;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
@@ -97,6 +98,8 @@ public class SearchSuggestService {
|
||||
|
||||
@Scheduled(initialDelayString = "${search.suggest.initial-delay:PT10S}",
|
||||
fixedDelayString = "${search.suggest.refresh-interval:PT10M}")
|
||||
// Словарь общий (таблица search_words) — пересобирает один экземпляр
|
||||
@SchedulerLock(name = "rebuildSearchDictionary", lockAtMostFor = "PT5M", lockAtLeastFor = "PT30S")
|
||||
@Transactional
|
||||
public void rebuildDictionary() {
|
||||
long start = System.currentTimeMillis();
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.krylov.refound.service;
|
||||
|
||||
import com.krylov.refound.config.ClusterMessaging;
|
||||
import com.krylov.refound.dto.ChatDto;
|
||||
import com.krylov.refound.dto.ChatPostDto;
|
||||
import com.krylov.refound.dto.MessageDto;
|
||||
@@ -24,7 +25,6 @@ import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.messaging.simp.SimpMessagingTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.transaction.support.TransactionSynchronization;
|
||||
@@ -40,7 +40,8 @@ public class ChatService {
|
||||
|
||||
private final ChatRepository chatRepository;
|
||||
private final MessageRepository messageRepository;
|
||||
private final SimpMessagingTemplate messagingTemplate;
|
||||
// Рассылка через Redis во все экземпляры: получатель может быть подключён к другому
|
||||
private final ClusterMessaging messaging;
|
||||
private final UserRepository userRepository;
|
||||
private final PostRepository postRepository;
|
||||
|
||||
@@ -163,8 +164,8 @@ public class ChatService {
|
||||
// Рассылаем только после коммита: иначе клиент, получив событие и перезапросив
|
||||
// историю, мог не увидеть ещё не закоммиченное сообщение
|
||||
afterCommit(() -> {
|
||||
messagingTemplate.convertAndSend("/topic/chat/" + chatId, dto);
|
||||
messagingTemplate.convertAndSend(
|
||||
messaging.convertAndSend("/topic/chat/" + chatId, dto);
|
||||
messaging.convertAndSend(
|
||||
"/topic/user/" + recipientId + "/unread",
|
||||
Map.of("chatId", chatId, "unreadCount", unreadCount)
|
||||
);
|
||||
|
||||
@@ -3,6 +3,7 @@ package com.krylov.refound.service;
|
||||
import com.krylov.refound.entity.Post;
|
||||
import com.krylov.refound.enums.PostStatus;
|
||||
import com.krylov.refound.repository.PostRepository;
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
@@ -13,6 +14,7 @@ import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import net.javacrumbs.shedlock.spring.annotation.SchedulerLock;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
@@ -22,6 +24,9 @@ import org.springframework.transaction.annotation.Transactional;
|
||||
@RequiredArgsConstructor
|
||||
public class SchedulerService {
|
||||
|
||||
/** Меньше lockAtMostFor задачи модерации (10 минут). */
|
||||
private static final Duration MODERATION_RUN_BUDGET = Duration.ofMinutes(8);
|
||||
|
||||
private final PostRepository postRepository;
|
||||
private final PostModerationExecutorService postModerationExecutorService;
|
||||
private final PostDeletionService postDeletionService;
|
||||
@@ -35,6 +40,7 @@ public class SchedulerService {
|
||||
* ссылки из чатов и файлы в MinIO (раньше файлы оставались мусором в бакете).
|
||||
*/
|
||||
@Scheduled(cron = "0 1 0 * * ?")
|
||||
@SchedulerLock(name = "deleteExpiredPosts", lockAtMostFor = "PT30M", lockAtLeastFor = "PT1M")
|
||||
@Transactional
|
||||
public void deleteExpiredPosts() {
|
||||
log.info("Starting scheduled cleanup of expired posts...");
|
||||
@@ -59,11 +65,16 @@ public class SchedulerService {
|
||||
* (залиты синхронно в PostService.create/update) — оригинальные MultipartFile
|
||||
* из запроса уже недоступны, поэтому PostModerationExecutorService скачивает их заново.
|
||||
*
|
||||
* При нескольких экземплярах прогон выполняет один (ShedLock), а результат
|
||||
* поста применяется условно (см. PostModerationExecutorService), так что
|
||||
* даже параллельная проверка не испортит статус.
|
||||
*
|
||||
* Сама обработка одного поста вынесена в отдельный бин: ему нужны собственные
|
||||
* короткие транзакции до и после вызова AI, а self-invocation внутри этого
|
||||
* класса обошёл бы Spring-прокси.
|
||||
*/
|
||||
@Scheduled(fixedDelay = 60_000)
|
||||
@SchedulerLock(name = "moderatePendingPosts", lockAtMostFor = "PT10M", lockAtLeastFor = "PT10S")
|
||||
public void moderatePendingPosts() {
|
||||
List<Long> pending = postRepository.findIdsByStatus(PostStatus.MODERATION);
|
||||
if (pending.isEmpty()) {
|
||||
@@ -71,7 +82,13 @@ public class SchedulerService {
|
||||
}
|
||||
|
||||
log.info("На модерации {} постов.", pending.size());
|
||||
long deadline = System.nanoTime() + MODERATION_RUN_BUDGET.toNanos();
|
||||
for (Long postId : pending) {
|
||||
// Не дольше, чем держится блокировка: иначе другой экземпляр начнёт тот же прогон
|
||||
if (System.nanoTime() > deadline) {
|
||||
log.info("Прогон модерации прерван по времени, остальные посты — в следующем запуске");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
postModerationExecutorService.moderateOne(postId);
|
||||
} catch (RuntimeException e) {
|
||||
|
||||
@@ -4,7 +4,7 @@ import com.krylov.refound.dto.advertising.TranscodingStatusDto;
|
||||
import com.krylov.refound.enums.advertising.TranscodingStatus;
|
||||
import com.krylov.refound.repository.advertising.AdvertisingRepository;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.messaging.simp.SimpMessagingTemplate;
|
||||
import com.krylov.refound.config.ClusterMessaging;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@@ -13,7 +13,8 @@ import org.springframework.transaction.annotation.Transactional;
|
||||
public class AdvertisingStatusService {
|
||||
|
||||
private final AdvertisingRepository advertisingRepository;
|
||||
private final SimpMessagingTemplate messagingTemplate;
|
||||
// Транскодинг идёт в любом экземпляре, а админ может быть подключён к другому
|
||||
private final ClusterMessaging messaging;
|
||||
|
||||
@Transactional
|
||||
public void markReady(Long advertisingId, String mediaKey) {
|
||||
@@ -32,7 +33,7 @@ public class AdvertisingStatusService {
|
||||
}
|
||||
|
||||
private void notifyStatusChange(Long advertisingId, TranscodingStatus status) {
|
||||
messagingTemplate.convertAndSend(
|
||||
messaging.convertAndSend(
|
||||
"/topic/ads/%d/status".formatted(advertisingId),
|
||||
new TranscodingStatusDto(advertisingId, status));
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ package com.krylov.refound.service.advertising;
|
||||
import com.krylov.refound.enums.advertising.TranscodingStatus;
|
||||
import com.krylov.refound.repository.advertising.FullscreenAdvertisingRepository;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.messaging.simp.SimpMessagingTemplate;
|
||||
import com.krylov.refound.config.ClusterMessaging;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@@ -12,7 +12,8 @@ import org.springframework.transaction.annotation.Transactional;
|
||||
public class FullscreenAdStatusService {
|
||||
|
||||
private final FullscreenAdvertisingRepository repository;
|
||||
private final SimpMessagingTemplate messagingTemplate;
|
||||
// Транскодинг идёт в любом экземпляре, а админ может быть подключён к другому
|
||||
private final ClusterMessaging messaging;
|
||||
|
||||
@Transactional
|
||||
public void markReady(Long id, String mediaKey) {
|
||||
@@ -30,7 +31,7 @@ public class FullscreenAdStatusService {
|
||||
}
|
||||
|
||||
private void notifyStatusChange(Long id, TranscodingStatus status) {
|
||||
messagingTemplate.convertAndSend(
|
||||
messaging.convertAndSend(
|
||||
"/topic/fullscreen-ads/%d/status".formatted(id),
|
||||
new com.krylov.refound.dto.advertising.TranscodingStatusDto(id, status));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.krylov.refound.config;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Map;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.springframework.data.redis.RedisConnectionFailureException;
|
||||
import org.springframework.data.redis.connection.DefaultMessage;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.messaging.simp.SimpMessagingTemplate;
|
||||
|
||||
class ClusterMessagingTest {
|
||||
|
||||
private SimpMessagingTemplate messagingTemplate;
|
||||
private StringRedisTemplate redis;
|
||||
private ObjectMapper objectMapper;
|
||||
private ClusterMessaging messaging;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
messagingTemplate = mock(SimpMessagingTemplate.class);
|
||||
redis = mock(StringRedisTemplate.class);
|
||||
objectMapper = new ObjectMapper().registerModule(new JavaTimeModule());
|
||||
messaging = new ClusterMessaging(messagingTemplate, redis, objectMapper, true);
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishesToRedisInsteadOfLocalBroker() {
|
||||
messaging.convertAndSend("/topic/chat/7", Map.of("content", "привет"));
|
||||
|
||||
ArgumentCaptor<String> json = ArgumentCaptor.forClass(String.class);
|
||||
verify(redis).convertAndSend(eq(ClusterMessaging.CHANNEL), json.capture());
|
||||
assertThat(json.getValue()).contains("/topic/chat/7").contains("привет");
|
||||
verify(messagingTemplate, never()).convertAndSend(anyString(), any(Object.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void messageFromRedisGoesToLocalBroker() throws Exception {
|
||||
String json = objectMapper.writeValueAsString(Map.of("destination", "/topic/chat/7",
|
||||
"payload", Map.of("content", "привет")));
|
||||
|
||||
messaging.onMessage(new DefaultMessage(ClusterMessaging.CHANNEL.getBytes(), json.getBytes(StandardCharsets.UTF_8)),
|
||||
null);
|
||||
|
||||
ArgumentCaptor<Object> payload = ArgumentCaptor.forClass(Object.class);
|
||||
verify(messagingTemplate).convertAndSend(eq("/topic/chat/7"), payload.capture());
|
||||
assertThat(((JsonNode) payload.getValue()).get("content").asText()).isEqualTo("привет");
|
||||
}
|
||||
|
||||
@Test
|
||||
void redisOutageFallsBackToLocalDelivery() {
|
||||
doThrow(new RedisConnectionFailureException("down")).when(redis).convertAndSend(anyString(), anyString());
|
||||
Map<String, String> payload = Map.of("content", "привет");
|
||||
|
||||
messaging.convertAndSend("/topic/chat/7", payload);
|
||||
|
||||
verify(messagingTemplate).convertAndSend("/topic/chat/7", (Object) payload);
|
||||
}
|
||||
|
||||
@Test
|
||||
void garbageFromRedisIsIgnored() {
|
||||
messaging.onMessage(new DefaultMessage(new byte[0], "not json".getBytes(StandardCharsets.UTF_8)), null);
|
||||
|
||||
verify(messagingTemplate, never()).convertAndSend(anyString(), any(Object.class));
|
||||
}
|
||||
}
|
||||
@@ -25,7 +25,7 @@ import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.messaging.simp.SimpMessagingTemplate;
|
||||
import com.krylov.refound.config.ClusterMessaging;
|
||||
|
||||
class ChatServiceTest {
|
||||
|
||||
@@ -41,7 +41,7 @@ class ChatServiceTest {
|
||||
userRepository = mock(UserRepository.class);
|
||||
postRepository = mock(PostRepository.class);
|
||||
messageRepository = mock(MessageRepository.class);
|
||||
chatService = new ChatService(chatRepository, messageRepository, mock(SimpMessagingTemplate.class),
|
||||
chatService = new ChatService(chatRepository, messageRepository, mock(ClusterMessaging.class),
|
||||
userRepository, postRepository);
|
||||
|
||||
when(userRepository.existsById(anyLong())).thenReturn(true);
|
||||
|
||||
Reference in New Issue
Block a user