Build the chat list with batch queries instead of five queries per chat
Interlocutors, posts, last messages (one subquery by max id) and unread counts (one GROUP BY) are loaded per list. The last message is now picked by id: createdAt is written in the sender's time zone and is not monotonic between users in different zones. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
package com.krylov.refound.repository;
|
||||
|
||||
import com.krylov.refound.entity.Message;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import org.springframework.data.domain.Page;
|
||||
@@ -14,7 +15,18 @@ public interface MessageRepository extends JpaRepository<Message, Long> {
|
||||
|
||||
Page<Message> findByChatIdOrderByCreatedAtDesc(Long chatId, Pageable pageable);
|
||||
|
||||
Optional<Message> findFirstByChatIdOrderByCreatedAtDesc(Long chatId);
|
||||
/**
|
||||
* Последнее сообщение каждого чата. «Последнее» — по id: createdAt пишется в
|
||||
* часовом поясе отправителя, и у собеседников из разных поясов не монотонен.
|
||||
*/
|
||||
@Query("SELECT m FROM Message m WHERE m.id IN "
|
||||
+ "(SELECT MAX(m2.id) FROM Message m2 WHERE m2.chatId IN :chatIds GROUP BY m2.chatId)")
|
||||
List<Message> findLastMessages(@Param("chatIds") Collection<Long> chatIds);
|
||||
|
||||
/** Непрочитанные сообщения от собеседника по каждому чату: строки (chatId, count). */
|
||||
@Query("SELECT m.chatId, COUNT(m) FROM Message m WHERE m.chatId IN :chatIds "
|
||||
+ "AND m.isRead = false AND m.senderId <> :userId GROUP BY m.chatId")
|
||||
List<Object[]> countUnreadByChat(@Param("chatIds") Collection<Long> chatIds, @Param("userId") Long userId);
|
||||
|
||||
long countByChatIdAndIsReadFalseAndSenderIdNot(Long chatId, Long userId);
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ import com.krylov.refound.entity.Chat;
|
||||
import com.krylov.refound.entity.Image;
|
||||
import com.krylov.refound.entity.Message;
|
||||
import com.krylov.refound.entity.Post;
|
||||
import com.krylov.refound.entity.User;
|
||||
import com.krylov.refound.enums.ErrorCode;
|
||||
import com.krylov.refound.exception.ApiException;
|
||||
import com.krylov.refound.repository.ChatRepository;
|
||||
@@ -18,7 +19,10 @@ import java.time.LocalDateTime;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -104,10 +108,12 @@ public class ChatService {
|
||||
record ChatWithActivity(ChatDto dto, LocalDateTime lastActivity) {
|
||||
}
|
||||
|
||||
return chatRepository.findAllByUserId(userId).stream()
|
||||
.map(c -> {
|
||||
ChatDto dto = toDto(c, userId);
|
||||
return new ChatWithActivity(dto, dto.getLastMessageAt() != null ? dto.getLastMessageAt() : c.getCreatedAt());
|
||||
List<Chat> chats = chatRepository.findAllByUserId(userId);
|
||||
Map<Long, Chat> byId = chats.stream().collect(Collectors.toMap(Chat::getId, Function.identity()));
|
||||
return toDtos(chats, userId).stream()
|
||||
.map(dto -> {
|
||||
LocalDateTime created = byId.get(dto.getId()).getCreatedAt();
|
||||
return new ChatWithActivity(dto, dto.getLastMessageAt() != null ? dto.getLastMessageAt() : created);
|
||||
})
|
||||
.sorted(Comparator.comparing(ChatWithActivity::lastActivity, Comparator.nullsLast(Comparator.reverseOrder())))
|
||||
.map(ChatWithActivity::dto)
|
||||
@@ -224,40 +230,65 @@ public class ChatService {
|
||||
}
|
||||
|
||||
private ChatDto toDto(Chat chat, Long currentUserId) {
|
||||
Long otherUserId = chat.getUserOneId().equals(currentUserId) ? chat.getUserTwoId() : chat.getUserOneId();
|
||||
return toDtos(List.of(chat), currentUserId).get(0);
|
||||
}
|
||||
|
||||
ChatDto dto = new ChatDto();
|
||||
dto.setId(chat.getId());
|
||||
dto.setOtherUserId(otherUserId);
|
||||
dto.setPostId(chat.getPostId());
|
||||
/**
|
||||
* Собирает ChatDto для списка чатов фиксированным числом запросов (собеседники,
|
||||
* объявления, последние сообщения, непрочитанные), а не пятью запросами на чат.
|
||||
*/
|
||||
private List<ChatDto> toDtos(List<Chat> chats, Long currentUserId) {
|
||||
if (chats.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
List<Long> chatIds = chats.stream().map(Chat::getId).toList();
|
||||
Map<Long, User> users = userRepository.findAllById(chats.stream()
|
||||
.map(chat -> otherUserId(chat, currentUserId)).distinct().toList()).stream()
|
||||
.collect(Collectors.toMap(User::getId, Function.identity()));
|
||||
Map<Long, Post> posts = postRepository.findAllById(chats.stream()
|
||||
.map(Chat::getPostId).filter(Objects::nonNull).distinct().toList()).stream()
|
||||
.collect(Collectors.toMap(Post::getId, Function.identity()));
|
||||
Map<Long, Message> lastMessages = messageRepository.findLastMessages(chatIds).stream()
|
||||
.collect(Collectors.toMap(Message::getChatId, Function.identity()));
|
||||
Map<Long, Long> unread = new HashMap<>();
|
||||
for (Object[] row : messageRepository.countUnreadByChat(chatIds, currentUserId)) {
|
||||
unread.put(((Number) row[0]).longValue(), ((Number) row[1]).longValue());
|
||||
}
|
||||
|
||||
userRepository.findById(otherUserId).ifPresent(user -> {
|
||||
dto.setOtherUserName(user.getName() + " " + user.getLastName());
|
||||
dto.setOtherUserAvatar(user.getAvatarUrl());
|
||||
});
|
||||
return chats.stream().map(chat -> {
|
||||
Long otherUserId = otherUserId(chat, currentUserId);
|
||||
ChatDto dto = new ChatDto();
|
||||
dto.setId(chat.getId());
|
||||
dto.setOtherUserId(otherUserId);
|
||||
dto.setPostId(chat.getPostId());
|
||||
|
||||
if (chat.getPostId() != null) {
|
||||
postRepository.findById(chat.getPostId()).ifPresent(post -> {
|
||||
User other = users.get(otherUserId);
|
||||
if (other != null) {
|
||||
dto.setOtherUserName(other.getName() + " " + other.getLastName());
|
||||
dto.setOtherUserAvatar(other.getAvatarUrl());
|
||||
}
|
||||
|
||||
Post post = chat.getPostId() == null ? null : posts.get(chat.getPostId());
|
||||
if (post != null) {
|
||||
ChatPostDto postDto = new ChatPostDto();
|
||||
postDto.setId(post.getId());
|
||||
postDto.setTitle(post.getTitle());
|
||||
postDto.setImages(post.getImages().stream().map(Image::getUrl).toList());
|
||||
dto.setPost(postDto);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// без N+1: берём только последнее сообщение, а не всю историю
|
||||
messageRepository.findFirstByChatIdOrderByCreatedAtDesc(chat.getId())
|
||||
.ifPresent(last -> {
|
||||
dto.setLastMessage(last.getContent());
|
||||
dto.setLastMessageAt(last.getCreatedAt());
|
||||
});
|
||||
Message last = lastMessages.get(chat.getId());
|
||||
if (last != null) {
|
||||
dto.setLastMessage(last.getContent());
|
||||
dto.setLastMessageAt(last.getCreatedAt());
|
||||
}
|
||||
dto.setUnreadCount(unread.getOrDefault(chat.getId(), 0L));
|
||||
return dto;
|
||||
}).toList();
|
||||
}
|
||||
|
||||
dto.setUnreadCount(
|
||||
messageRepository.countByChatIdAndIsReadFalseAndSenderIdNot(chat.getId(), currentUserId)
|
||||
);
|
||||
|
||||
return dto;
|
||||
private static Long otherUserId(Chat chat, Long currentUserId) {
|
||||
return chat.getUserOneId().equals(currentUserId) ? chat.getUserTwoId() : chat.getUserOneId();
|
||||
}
|
||||
|
||||
private MessageDto toMessageDto(Message m) {
|
||||
|
||||
Reference in New Issue
Block a user