-
Notifications
You must be signed in to change notification settings - Fork 2
[Chat] Redis Stream 기반 채팅 메세지 저장&조회 #204
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
cf21973
docs: 채팅방 description 수정
heygeeji 7659cb9
chore: WebSocket 엔드포인트 수정
heygeeji 0e030b3
feat: 채팅 메세지 Redis Stream에 저장
heygeeji a7af6ed
refactor: dto 패키지 변경
heygeeji 63d8025
refactor: 채팅 정책 TTL 조정 및 문서화 개선
heygeeji 65711fc
feat: Redis Stream 기반 채팅 메시지 조회 구현
heygeeji a1b851e
feat: 채팅 메시지 전송 시 유저 정보 Redis 캐싱 적용
heygeeji 99980b6
feat: 유저 닉네임 변경 시 채팅 유저 정보 캐시 무효화 처리
heygeeji File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
67 changes: 67 additions & 0 deletions
67
.../java/com/back/web7_9_codecrete_be/domain/chats/controller/ChatMessageReadController.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,67 @@ | ||
| package com.back.web7_9_codecrete_be.domain.chats.controller; | ||
|
|
||
| import java.util.List; | ||
|
|
||
| import org.springframework.web.bind.annotation.GetMapping; | ||
| import org.springframework.web.bind.annotation.PathVariable; | ||
| import org.springframework.web.bind.annotation.RequestMapping; | ||
| import org.springframework.web.bind.annotation.RequestParam; | ||
| import org.springframework.web.bind.annotation.RestController; | ||
|
|
||
| import com.back.web7_9_codecrete_be.domain.chats.dto.response.ChatReadResponse; | ||
| import com.back.web7_9_codecrete_be.domain.chats.service.ChatMessageReadService; | ||
| import com.back.web7_9_codecrete_be.global.rsData.RsData; | ||
|
|
||
| import io.swagger.v3.oas.annotations.Operation; | ||
| import io.swagger.v3.oas.annotations.Parameter; | ||
| import io.swagger.v3.oas.annotations.tags.Tag; | ||
| import lombok.RequiredArgsConstructor; | ||
|
|
||
| @Tag(name = "Chat", description = "채팅 메시지 조회 API") | ||
| @RestController | ||
| @RequestMapping("/api/v1/chats") | ||
| @RequiredArgsConstructor | ||
| public class ChatMessageReadController { | ||
|
|
||
| private final ChatMessageReadService chatMessageReadService; | ||
|
|
||
| @Operation( | ||
| summary = "채팅 메시지 조회 (cursor 기반 무한 스크롤)", | ||
| description = """ | ||
| 채팅 메시지를 cursor(before) 기준으로 조회합니다. | ||
|
|
||
| - before 미전달 시: 최신 메시지를 조회합니다. | ||
| - before 전달 시: 해당 cursor 이전의 메시지를 조회합니다. | ||
| """ | ||
| ) | ||
| @GetMapping("/{concertId}/messages") | ||
| public RsData<List<ChatReadResponse>> getMessages( | ||
| @Parameter( | ||
| description = "공연 ID", | ||
| example = "1", | ||
| required = true | ||
| ) | ||
| @PathVariable Long concertId, | ||
|
|
||
| @Parameter( | ||
| description = """ | ||
| 조회 기준 cursor (Redis Stream ID). | ||
| 해당 값이 주어지면, 그 이전의 채팅 메시지를 조회합니다. | ||
| """, | ||
| example = "1734940012345-0", | ||
| required = false | ||
| ) | ||
| @RequestParam(required = false) String before, | ||
|
|
||
| @Parameter( | ||
| description = "한 번에 조회할 메시지 개수 (기본값: 20)", | ||
| example = "20", | ||
| required = false | ||
| ) | ||
| @RequestParam(required = false) Integer size | ||
| ) { | ||
| return RsData.success( | ||
| chatMessageReadService.getMessages(concertId, before, size) | ||
| ); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
2 changes: 1 addition & 1 deletion
2
.../domain/chats/dto/ChatMessageRequest.java → ...chats/dto/request/ChatMessageRequest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
2 changes: 1 addition & 1 deletion
2
...domain/chats/dto/ChatMessageResponse.java → ...ats/dto/response/ChatMessageResponse.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
35 changes: 35 additions & 0 deletions
35
src/main/java/com/back/web7_9_codecrete_be/domain/chats/dto/response/ChatReadResponse.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,35 @@ | ||
| package com.back.web7_9_codecrete_be.domain.chats.dto.response; | ||
|
|
||
| import java.time.LocalDateTime; | ||
|
|
||
| import io.swagger.v3.oas.annotations.media.Schema; | ||
| import lombok.AllArgsConstructor; | ||
| import lombok.Getter; | ||
| import lombok.NoArgsConstructor; | ||
| import lombok.Setter; | ||
|
|
||
| @Getter | ||
| @Setter | ||
| @NoArgsConstructor | ||
| @AllArgsConstructor | ||
| @Schema(description = "채팅 메시지 조회 응답") | ||
| public class ChatReadResponse { | ||
|
|
||
| @Schema(description = "Redis Stream 메시지 ID (before로 전달하면, 해당 메시지 이전 메시지를 조회할 수 있습니다)", example = "1700000123456-0") | ||
| private String messageId; | ||
|
|
||
| @Schema(description = "공연 ID", example = "1") | ||
| private Long concertId; | ||
|
|
||
| @Schema(description = "발신자 ID", example = "2") | ||
| private Long senderId; | ||
|
|
||
| @Schema(description = "발신자 닉네임", example = "테스트 유저") | ||
| private String senderName; | ||
|
|
||
| @Schema(description = "메시지 내용", example = "안녕하세요") | ||
| private String content; | ||
|
|
||
| @Schema(description = "전송 시각") | ||
| private LocalDateTime sentDate; | ||
| } |
14 changes: 14 additions & 0 deletions
14
src/main/java/com/back/web7_9_codecrete_be/domain/chats/dto/response/ChatUserCache.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| package com.back.web7_9_codecrete_be.domain.chats.dto.response; | ||
|
|
||
| import lombok.AllArgsConstructor; | ||
| import lombok.Getter; | ||
| import lombok.NoArgsConstructor; | ||
|
|
||
| @Getter | ||
| @NoArgsConstructor | ||
| @AllArgsConstructor | ||
| public class ChatUserCache { | ||
|
|
||
| private Long userId; | ||
| private String nickname; | ||
| } |
128 changes: 128 additions & 0 deletions
128
src/main/java/com/back/web7_9_codecrete_be/domain/chats/repository/ChatStreamRepository.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,128 @@ | ||
| package com.back.web7_9_codecrete_be.domain.chats.repository; | ||
|
|
||
| import java.time.Duration; | ||
| import java.time.LocalDateTime; | ||
| import java.util.HashMap; | ||
| import java.util.List; | ||
| import java.util.Map; | ||
| import java.util.Objects; | ||
|
|
||
| import org.springframework.data.domain.Range; | ||
| import org.springframework.data.redis.connection.Limit; | ||
| import org.springframework.data.redis.connection.stream.MapRecord; | ||
| import org.springframework.data.redis.connection.stream.StreamRecords; | ||
| import org.springframework.data.redis.core.RedisTemplate; | ||
| import org.springframework.stereotype.Repository; | ||
|
|
||
| import com.back.web7_9_codecrete_be.domain.chats.dto.response.ChatMessageResponse; | ||
| import com.back.web7_9_codecrete_be.domain.chats.dto.response.ChatReadResponse; | ||
|
|
||
| import lombok.RequiredArgsConstructor; | ||
|
|
||
| @Repository | ||
| @RequiredArgsConstructor | ||
| public class ChatStreamRepository { | ||
|
|
||
| private final RedisTemplate<String, Object> redisTemplate; | ||
|
|
||
| private String streamKey(Long concertId) { | ||
| return "chat:stream:" + concertId; | ||
| } | ||
|
|
||
| /** 저장 */ | ||
| public void save(ChatMessageResponse message) { | ||
| String key = streamKey(message.getConcertId()); | ||
|
|
||
| Map<String, String> fields = new HashMap<>(); | ||
| fields.put("concertId", message.getConcertId().toString()); | ||
| fields.put("senderId", message.getSenderId().toString()); | ||
| fields.put("senderName", message.getSenderName()); | ||
| fields.put("content", message.getContent()); | ||
| fields.put("sentDate", message.getSentDate().toString()); | ||
|
|
||
| redisTemplate.opsForStream().add( | ||
| StreamRecords.newRecord() | ||
| .in(key) | ||
| .ofMap(fields) | ||
| ); | ||
| } | ||
|
|
||
| public boolean hasTtl(Long concertId) { | ||
| Long ttl = redisTemplate.getExpire(streamKey(concertId)); | ||
| return ttl != null && ttl >= 0; | ||
| } | ||
|
|
||
| public void setTtl(Long concertId, Duration ttl) { | ||
| redisTemplate.expire(streamKey(concertId), ttl); | ||
| } | ||
|
|
||
| /** 조회 */ | ||
| // 채팅방 진입시 가장 최신 메시지 size개 조회 | ||
| public List<ChatReadResponse> findLatest(Long concertId, int size) { | ||
|
|
||
| List<MapRecord<String, Object, Object>> records = | ||
| redisTemplate.opsForStream().reverseRange( | ||
| streamKey(concertId), | ||
| Range.unbounded(), | ||
| Limit.limit().count(size) | ||
| ); | ||
|
|
||
| return toResponses(records); | ||
| } | ||
|
|
||
| // cursor(before) 기반 과거 메시지 조회 | ||
| // beforeMessageId보다 이전에 있던 메시지들 중 최신 size개 조회 | ||
| public List<ChatReadResponse> findBefore( | ||
| Long concertId, | ||
| String beforeMessageId, | ||
| int size | ||
| ) { | ||
| String exclusiveBeforeId = exclusiveBefore(beforeMessageId); | ||
|
|
||
| List<MapRecord<String, Object, Object>> records = | ||
| redisTemplate.opsForStream().reverseRange( | ||
| streamKey(concertId), | ||
| Range.leftOpen("0-0", exclusiveBeforeId), | ||
| Limit.limit().count(size) | ||
| ); | ||
|
|
||
| return toResponses(records); | ||
| } | ||
|
|
||
| private List<ChatReadResponse> toResponses( | ||
| List<MapRecord<String, Object, Object>> records | ||
| ) { | ||
| if (records == null || records.isEmpty()) { | ||
| return List.of(); | ||
| } | ||
|
|
||
| return records.stream() | ||
| .map(record -> { | ||
| Map<Object, Object> v = record.getValue(); | ||
|
|
||
| return new ChatReadResponse( | ||
| record.getId().getValue(), | ||
| Long.valueOf(v.get("concertId").toString()), | ||
| Long.valueOf(v.get("senderId").toString()), | ||
| v.get("senderName").toString(), | ||
| v.get("content").toString(), | ||
| LocalDateTime.parse(v.get("sentDate").toString()) | ||
| ); | ||
| }) | ||
| .filter(Objects::nonNull) | ||
| .toList(); | ||
| } | ||
|
|
||
| private String exclusiveBefore(String messageId) { | ||
| String[] parts = messageId.split("-"); | ||
| long time = Long.parseLong(parts[0]); // 밀리초 타임스탬프 | ||
| long seq = Long.parseLong(parts[1]); // 같은 밀리초 내 순번 | ||
|
|
||
| if (seq > 0) { | ||
| return time + "-" + (seq - 1); | ||
| } | ||
|
|
||
| // seq == 0 인 경우, timestamp를 1 감소 | ||
| return (time - 1) + "-0"; | ||
| } | ||
| } | ||
39 changes: 39 additions & 0 deletions
39
src/main/java/com/back/web7_9_codecrete_be/domain/chats/service/ChatMessageReadService.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,39 @@ | ||
| package com.back.web7_9_codecrete_be.domain.chats.service; | ||
|
|
||
| import java.util.List; | ||
|
|
||
| import org.springframework.stereotype.Service; | ||
|
|
||
| import com.back.web7_9_codecrete_be.domain.chats.dto.response.ChatReadResponse; | ||
| import com.back.web7_9_codecrete_be.domain.chats.repository.ChatStreamRepository; | ||
|
|
||
| import lombok.RequiredArgsConstructor; | ||
|
|
||
| @Service | ||
| @RequiredArgsConstructor | ||
| public class ChatMessageReadService { | ||
|
|
||
| private static final int DEFAULT_SIZE = 20; | ||
| private static final int MAX_SIZE = 50; | ||
|
|
||
| private final ChatStreamRepository chatStreamRepository; | ||
|
|
||
| public List<ChatReadResponse> getMessages( | ||
| Long concertId, | ||
| String before, | ||
| Integer size | ||
| ) { | ||
| int limit = Math.min( | ||
| size != null ? size : DEFAULT_SIZE, | ||
| MAX_SIZE | ||
| ); | ||
|
|
||
| // 최초 진입 | ||
| if (before == null || before.isBlank()) { | ||
| return chatStreamRepository.findLatest(concertId, limit); | ||
| } | ||
|
|
||
| // 이전 메시지 조회 (무한 스크롤) | ||
| return chatStreamRepository.findBefore(concertId, before, limit); | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
같은 시간 내에서도 순번을 정하신것 좋은 방법인 것 같습니다