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

@@ -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)
);