diff --git a/build.gradle b/build.gradle index d4fb98f..e6ed2eb 100644 --- a/build.gradle +++ b/build.gradle @@ -65,6 +65,11 @@ dependencies { //WebClient implementation 'org.springframework.boot:spring-boot-starter-webflux' + // Фоновые задачи (@Scheduled) при нескольких экземплярах выполняет только один — + // блокировка в Redis + implementation 'net.javacrumbs.shedlock:shedlock-spring:6.10.0' + implementation 'net.javacrumbs.shedlock:shedlock-provider-redis-spring:6.10.0' + implementation 'org.springframework.retry:spring-retry' implementation 'org.springframework:spring-aspects' diff --git a/src/main/java/com/krylov/refound/config/ClusterMessaging.java b/src/main/java/com/krylov/refound/config/ClusterMessaging.java new file mode 100644 index 0000000..f102499 --- /dev/null +++ b/src/main/java/com/krylov/refound/config/ClusterMessaging.java @@ -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-сообщений во все экземпляры приложения. + * + *
WebSocket-брокер (simple broker) живёт в памяти процесса: подписчики, + * подключённые к другому экземпляру, сообщение не получили бы. Поэтому событие + * публикуется в канал Redis {@value #CHANNEL}, каждый экземпляр (включая + * отправителя) получает его и отдаёт своему локальному брокеру — а тот своим + * подписчикам. Права на подписку по-прежнему проверяет WsStompInterceptor в + * том экземпляре, где подключён клиент. + * + *
Если 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; + } +} diff --git a/src/main/java/com/krylov/refound/config/RedisConfig.java b/src/main/java/com/krylov/refound/config/RedisConfig.java index 38a2b3b..661fda3 100644 --- a/src/main/java/com/krylov/refound/config/RedisConfig.java +++ b/src/main/java/com/krylov/refound/config/RedisConfig.java @@ -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; } -} \ No newline at end of file + + /** Подписка на канал рассылки 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; + } +} diff --git a/src/main/java/com/krylov/refound/config/SchedulerLockConfig.java b/src/main/java/com/krylov/refound/config/SchedulerLockConfig.java new file mode 100644 index 0000000..abbe03a --- /dev/null +++ b/src/main/java/com/krylov/refound/config/SchedulerLockConfig.java @@ -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:<имя задачи>}); остальные пропускают запуск. + * + *
Если 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);
+ }
+}
diff --git a/src/main/java/com/krylov/refound/search/SearchSuggestService.java b/src/main/java/com/krylov/refound/search/SearchSuggestService.java
index 6d930aa..13100b4 100644
--- a/src/main/java/com/krylov/refound/search/SearchSuggestService.java
+++ b/src/main/java/com/krylov/refound/search/SearchSuggestService.java
@@ -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();
diff --git a/src/main/java/com/krylov/refound/service/ChatService.java b/src/main/java/com/krylov/refound/service/ChatService.java
index 61ba7d0..8cc5fad 100644
--- a/src/main/java/com/krylov/refound/service/ChatService.java
+++ b/src/main/java/com/krylov/refound/service/ChatService.java
@@ -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)
);
diff --git a/src/main/java/com/krylov/refound/service/SchedulerService.java b/src/main/java/com/krylov/refound/service/SchedulerService.java
index 63f3b34..a44c238 100644
--- a/src/main/java/com/krylov/refound/service/SchedulerService.java
+++ b/src/main/java/com/krylov/refound/service/SchedulerService.java
@@ -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