-
Notifications
You must be signed in to change notification settings - Fork 1
[BE-Feat] Redis 사용 세팅 #98
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
Conversation
key: {discussionId}:{minuteKey} 로 2byte의 비트맵을 저장
RedisTemplate 사용하여 value를 비트단위로 수정 가능
작성한 RedisTemplate 테스트 DiscussionBitmapService 작동 테스트
WalkthroughThis pull request integrates Redis support into the backend. It adds a Redis dependency and Testcontainers dependency in the build file. A new Redis configuration class is introduced to enable Redis connectivity with a custom RedisTemplate. Additionally, a service for managing bitmap data in Redis is implemented, along with tests to verify bitmap operations and byte array storage. A test container class is also provided to facilitate running Redis during tests using a Docker container. Changes
Sequence Diagram(s)sequenceDiagram
actor Client
participant Service as DiscussionBitmapService
participant Template as RedisTemplate
participant Redis as Redis Server
Client->>Service: initializeBitmap(discussionId, dateTime)
Service->>Template: Store initial bitmap
Template->>Redis: SET key with initial bitmap
Note over Template,Redis: Bitmap initialized
Client->>Service: setBitValue(discussionId, dateTime, bitOffset, true)
Service->>Template: SETBIT key at bitOffset
Template->>Redis: Update bit value
Note over Template,Redis: Bit operation completed
Client->>Service: getBitValue(discussionId, dateTime, bitOffset)
Service->>Template: GETBIT key at bitOffset
Template->>Redis: Retrieve bit value
Redis-->>Template: bit value
Template-->>Service: Return bit value
Service-->>Client: Deliver result
Poem
Tip 🌐 Web search-backed reviews and chat
✨ Finishing Touches
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
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.
Actionable comments posted: 5
🧹 Nitpick comments (7)
backend/src/main/java/endolphin/backend/global/config/RedisConfig.java (1)
22-25: Consider adding connection pool settings for production use.The Redis connection factory could benefit from connection pool configuration to handle high concurrent loads efficiently.
@Bean public RedisConnectionFactory redisConnectionFactory() { - return new LettuceConnectionFactory(host, port); + LettuceConnectionFactory factory = new LettuceConnectionFactory(host, port); + factory.setShareNativeConnection(false); // Each connection is thread-safe + return factory; }backend/src/test/java/endolphin/backend/global/redis/DiscussionBitmapServiceTest.java (1)
38-43: Consider extracting bit manipulation logic.The bit manipulation logic for verification could be moved to a utility class for reuse.
+ private boolean extractBit(byte[] data, int offset) { + int byteIndex = offset / 8; + int bitPosition = offset % 8; + return ((data[byteIndex] >> (7 - bitPosition)) & 1) == 1; + }backend/src/main/java/endolphin/backend/global/redis/DiscussionBitmapService.java (4)
18-20: Add input validation for discussionId.The method should validate that discussionId is not null to prevent NullPointerException.
private String buildRedisKey(Long discussionId, long minuteKey) { + if (discussionId == null) { + throw new IllegalArgumentException("discussionId must not be null"); + } return discussionId + ":" + minuteKey; }
25-27: Add input validation for dateTime.The method should validate that dateTime is not null to prevent NullPointerException.
private long convertToMinuteKey(LocalDateTime dateTime) { + if (dateTime == null) { + throw new IllegalArgumentException("dateTime must not be null"); + } return dateTime.toEpochSecond(ZoneOffset.UTC) / 60; }
35-41: Consider adding key existence check and make byteSize a constant.
- Add a check to prevent overwriting existing data.
- Define byteSize as a constant since it's a fixed value.
+ private static final int BITMAP_SIZE_BYTES = 2; + public void initializeBitmap(Long discussionId, LocalDateTime dateTime) { - int byteSize = 2; long minuteKey = convertToMinuteKey(dateTime); String redisKey = buildRedisKey(discussionId, minuteKey); - byte[] initialData = new byte[byteSize]; + if (redisTemplate.hasKey(redisKey)) { + throw new IllegalStateException("Bitmap already exists for key: " + redisKey); + } + byte[] initialData = new byte[BITMAP_SIZE_BYTES]; redisTemplate.opsForValue().set(redisKey, initialData); }
80-84: Add validation for returned data size.Verify that the returned data is either null or exactly 2 bytes.
public byte[] getBitmapData(Long discussionId, LocalDateTime dateTime) { long minuteKey = convertToMinuteKey(dateTime); String redisKey = buildRedisKey(discussionId, minuteKey); - return redisTemplate.opsForValue().get(redisKey); + byte[] data = redisTemplate.opsForValue().get(redisKey); + if (data != null && data.length != BITMAP_SIZE_BYTES) { + throw new IllegalStateException("Invalid bitmap data size: " + data.length); + } + return data; }backend/build.gradle (1)
57-58: Consider adding testcontainers-redis module.While the core testcontainers dependency is added, consider also adding the Redis-specific module for better Redis container support.
// test-containers testImplementation "org.testcontainers:testcontainers:1.20.4" +testImplementation "org.testcontainers:testcontainers-redis:1.20.4"
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (6)
backend/build.gradle(1 hunks)backend/src/main/java/endolphin/backend/global/config/RedisConfig.java(1 hunks)backend/src/main/java/endolphin/backend/global/redis/DiscussionBitmapService.java(1 hunks)backend/src/test/java/endolphin/backend/global/redis/DiscussionBitmapServiceTest.java(1 hunks)backend/src/test/java/endolphin/backend/global/redis/RedisTemplateTest.java(1 hunks)backend/src/test/java/endolphin/backend/global/redis/RedisTestContainer.java(1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
- GitHub Check: Send PR Notification to Reviewers
🔇 Additional comments (4)
backend/src/main/java/endolphin/backend/global/config/RedisConfig.java (1)
32-42: Consider adding SSL/TLS configuration for secure Redis connections.For production environments, secure communication with Redis should be configured.
backend/src/test/java/endolphin/backend/global/redis/RedisTestContainer.java (1)
14-14: Consider upgrading Redis version for test container.The current Redis version (6) is outdated. Consider using a more recent version for testing.
✅ Verification successful
🌐 Web query:
What is the latest stable version of Redis?Length of output: 1145
Redis Test Container Version Update Needed
- The test container currently uses
redis:6-alpine, which is outdated.- As of February 2025, the latest stable Redis version is 7.4. Upgrading to an image like
redis:7.4-alpineis recommended.backend/build.gradle (2)
50-52: LGTM! Redis dependency added correctly.The Redis starter dependency is correctly added and will provide all necessary Redis components.
3-3: Verify Spring Boot version compatibility.Spring Boot version 3.4.2 seems incorrect as it's beyond the latest known version.
✅ Verification successful
🌐 Web query:
What is the latest version of Spring Boot?Length of output: 1427
Subject: Spring Boot version 3.4.2 is Compatible
The Spring Boot version specified (
3.4.2) matches the latest stable version as of February 2025. No changes are needed.
| static { | ||
| GenericContainer<?> REDIS_CONTAINER = | ||
| new GenericContainer<>(DockerImageName.parse(REDIS_DOCKER_IMAGE)) | ||
| .withExposedPorts(6379) | ||
| .withReuse(true); | ||
|
|
||
| REDIS_CONTAINER.start(); | ||
|
|
||
| System.setProperty("spring.data.redis.host", REDIS_CONTAINER.getHost()); | ||
| System.setProperty("spring.data.redis.port", | ||
| REDIS_CONTAINER.getMappedPort(6379).toString()); | ||
| } |
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.
🛠️ Refactor suggestion
Consider using @DynamicPropertySource instead of static block.
Using a static block for container initialization can cause issues with Spring context lifecycle. Consider using @DynamicPropertySource for better integration with Spring Boot test context.
- static {
- GenericContainer<?> REDIS_CONTAINER =
- new GenericContainer<>(DockerImageName.parse(REDIS_DOCKER_IMAGE))
- .withExposedPorts(6379)
- .withReuse(true);
-
- REDIS_CONTAINER.start();
-
- System.setProperty("spring.data.redis.host", REDIS_CONTAINER.getHost());
- System.setProperty("spring.data.redis.port",
- REDIS_CONTAINER.getMappedPort(6379).toString());
- }
+ static final GenericContainer<?> REDIS_CONTAINER;
+
+ static {
+ REDIS_CONTAINER = new GenericContainer<>(DockerImageName.parse(REDIS_DOCKER_IMAGE))
+ .withExposedPorts(6379)
+ .withReuse(true);
+ REDIS_CONTAINER.start();
+ }
+
+ @DynamicPropertySource
+ static void redisProperties(DynamicPropertyRegistry registry) {
+ registry.add("spring.data.redis.host", REDIS_CONTAINER::getHost);
+ registry.add("spring.data.redis.port", () ->
+ REDIS_CONTAINER.getMappedPort(6379).toString());
+ }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| static { | |
| GenericContainer<?> REDIS_CONTAINER = | |
| new GenericContainer<>(DockerImageName.parse(REDIS_DOCKER_IMAGE)) | |
| .withExposedPorts(6379) | |
| .withReuse(true); | |
| REDIS_CONTAINER.start(); | |
| System.setProperty("spring.data.redis.host", REDIS_CONTAINER.getHost()); | |
| System.setProperty("spring.data.redis.port", | |
| REDIS_CONTAINER.getMappedPort(6379).toString()); | |
| } | |
| static final GenericContainer<?> REDIS_CONTAINER; | |
| static { | |
| REDIS_CONTAINER = new GenericContainer<>(DockerImageName.parse(REDIS_DOCKER_IMAGE)) | |
| .withExposedPorts(6379) | |
| .withReuse(true); | |
| REDIS_CONTAINER.start(); | |
| } | |
| @DynamicPropertySource | |
| static void redisProperties(DynamicPropertyRegistry registry) { | |
| registry.add("spring.data.redis.host", REDIS_CONTAINER::getHost); | |
| registry.add("spring.data.redis.port", () -> | |
| REDIS_CONTAINER.getMappedPort(6379).toString()); | |
| } |
| public void testSetAndGetByteArray() { | ||
| String key = "test:bytearray"; | ||
| byte[] expected = new byte[] {10, 20, 30, 40, 50}; | ||
|
|
||
| // 값 저장 | ||
| redisTemplate.opsForValue().set(key, expected); | ||
|
|
||
| // 값 조회 | ||
| byte[] actual = redisTemplate.opsForValue().get(key); | ||
|
|
||
| assertThat(actual).isEqualTo(expected); | ||
| } |
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.
🛠️ Refactor suggestion
Add more test cases and cleanup.
The test should include more edge cases and cleanup Redis after test execution.
+ @AfterEach
+ void cleanup() {
+ redisTemplate.delete("test:bytearray");
+ }
@Test
@DisplayName("작성한 Redis template 테스트")
public void testSetAndGetByteArray() {
// ... existing test ...
}
+ @Test
+ @DisplayName("대용량 바이트 배열 테스트")
+ public void testLargeByteArray() {
+ String key = "test:large:bytearray";
+ byte[] expected = new byte[1024 * 1024]; // 1MB
+ new Random().nextBytes(expected);
+
+ redisTemplate.opsForValue().set(key, expected);
+ byte[] actual = redisTemplate.opsForValue().get(key);
+
+ assertThat(actual).isEqualTo(expected);
+ }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| public void testSetAndGetByteArray() { | |
| String key = "test:bytearray"; | |
| byte[] expected = new byte[] {10, 20, 30, 40, 50}; | |
| // 값 저장 | |
| redisTemplate.opsForValue().set(key, expected); | |
| // 값 조회 | |
| byte[] actual = redisTemplate.opsForValue().get(key); | |
| assertThat(actual).isEqualTo(expected); | |
| } | |
| @AfterEach | |
| void cleanup() { | |
| redisTemplate.delete("test:bytearray"); | |
| } | |
| @Test | |
| @DisplayName("작성한 Redis template 테스트") | |
| public void testSetAndGetByteArray() { | |
| String key = "test:bytearray"; | |
| byte[] expected = new byte[] {10, 20, 30, 40, 50}; | |
| // 값 저장 | |
| redisTemplate.opsForValue().set(key, expected); | |
| // 값 조회 | |
| byte[] actual = redisTemplate.opsForValue().get(key); | |
| assertThat(actual).isEqualTo(expected); | |
| } | |
| @Test | |
| @DisplayName("대용량 바이트 배열 테스트") | |
| public void testLargeByteArray() { | |
| String key = "test:large:bytearray"; | |
| byte[] expected = new byte[1024 * 1024]; // 1MB | |
| new Random().nextBytes(expected); | |
| redisTemplate.opsForValue().set(key, expected); | |
| byte[] actual = redisTemplate.opsForValue().get(key); | |
| assertThat(actual).isEqualTo(expected); | |
| } |
| public void testInitializeAndBitOperations() { | ||
| Long discussionId = 100L; | ||
| LocalDateTime dateTime = LocalDateTime.now(); | ||
|
|
||
| // 1. 초기화: 해당 논의 및 시각에 대해 16비트 크기의 비트맵을 생성하여 Redis에 저장 | ||
| bitmapService.initializeBitmap(discussionId, dateTime); | ||
|
|
||
| // 2. 오프셋 5의 비트를 true로 설정 | ||
| Boolean previousValue = bitmapService.setBitValue(discussionId, dateTime, 5, true); | ||
| // 초기화된 비트맵은 모두 0이므로 이전 값은 false여야 함 | ||
| assertThat(previousValue).isFalse(); | ||
|
|
||
| // 3. 수정된 비트 조회: 오프셋 5의 비트 값이 true인지 확인 | ||
| Boolean bitValue = bitmapService.getBitValue(discussionId, dateTime, 5); | ||
| assertThat(bitValue).isTrue(); | ||
|
|
||
| // 4. 전체 비트맵 데이터 조회 및 검증 | ||
| byte[] bitmapData = bitmapService.getBitmapData(discussionId, dateTime); | ||
| int byteIndex = 5 / 8; // 0 | ||
| int bitPosition = 5 % 8; // 5 | ||
| // big-endian 순서로 확인: (7 - bitPosition) | ||
| boolean extractedBit = ((bitmapData[byteIndex] >> (7 - bitPosition)) & 1) == 1; | ||
| assertThat(extractedBit).isTrue(); | ||
| } |
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.
🛠️ Refactor suggestion
Add error case tests and boundary checks.
The test should include error cases and boundary checks for bitmap operations.
+ @Test
+ @DisplayName("잘못된 오프셋 값에 대한 예외 처리 테스트")
+ public void testInvalidOffset() {
+ Long discussionId = 100L;
+ LocalDateTime dateTime = LocalDateTime.now();
+ bitmapService.initializeBitmap(discussionId, dateTime);
+
+ assertThatThrownBy(() ->
+ bitmapService.setBitValue(discussionId, dateTime, -1, true))
+ .isInstanceOf(IllegalArgumentException.class);
+
+ assertThatThrownBy(() ->
+ bitmapService.setBitValue(discussionId, dateTime, 16, true))
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+
+ @Test
+ @DisplayName("존재하지 않는 비트맵에 대한 예외 처리 테스트")
+ public void testNonExistentBitmap() {
+ Long discussionId = 999L;
+ LocalDateTime dateTime = LocalDateTime.now();
+
+ assertThatThrownBy(() ->
+ bitmapService.getBitValue(discussionId, dateTime, 0))
+ .isInstanceOf(IllegalStateException.class);
+ }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| public void testInitializeAndBitOperations() { | |
| Long discussionId = 100L; | |
| LocalDateTime dateTime = LocalDateTime.now(); | |
| // 1. 초기화: 해당 논의 및 시각에 대해 16비트 크기의 비트맵을 생성하여 Redis에 저장 | |
| bitmapService.initializeBitmap(discussionId, dateTime); | |
| // 2. 오프셋 5의 비트를 true로 설정 | |
| Boolean previousValue = bitmapService.setBitValue(discussionId, dateTime, 5, true); | |
| // 초기화된 비트맵은 모두 0이므로 이전 값은 false여야 함 | |
| assertThat(previousValue).isFalse(); | |
| // 3. 수정된 비트 조회: 오프셋 5의 비트 값이 true인지 확인 | |
| Boolean bitValue = bitmapService.getBitValue(discussionId, dateTime, 5); | |
| assertThat(bitValue).isTrue(); | |
| // 4. 전체 비트맵 데이터 조회 및 검증 | |
| byte[] bitmapData = bitmapService.getBitmapData(discussionId, dateTime); | |
| int byteIndex = 5 / 8; // 0 | |
| int bitPosition = 5 % 8; // 5 | |
| // big-endian 순서로 확인: (7 - bitPosition) | |
| boolean extractedBit = ((bitmapData[byteIndex] >> (7 - bitPosition)) & 1) == 1; | |
| assertThat(extractedBit).isTrue(); | |
| } | |
| public void testInitializeAndBitOperations() { | |
| Long discussionId = 100L; | |
| LocalDateTime dateTime = LocalDateTime.now(); | |
| // 1. 초기화: 해당 논의 및 시각에 대해 16비트 크기의 비트맵을 생성하여 Redis에 저장 | |
| bitmapService.initializeBitmap(discussionId, dateTime); | |
| // 2. 오프셋 5의 비트를 true로 설정 | |
| Boolean previousValue = bitmapService.setBitValue(discussionId, dateTime, 5, true); | |
| // 초기화된 비트맵은 모두 0이므로 이전 값은 false여야 함 | |
| assertThat(previousValue).isFalse(); | |
| // 3. 수정된 비트 조회: 오프셋 5의 비트 값이 true인지 확인 | |
| Boolean bitValue = bitmapService.getBitValue(discussionId, dateTime, 5); | |
| assertThat(bitValue).isTrue(); | |
| // 4. 전체 비트맵 데이터 조회 및 검증 | |
| byte[] bitmapData = bitmapService.getBitmapData(discussionId, dateTime); | |
| int byteIndex = 5 / 8; // 0 | |
| int bitPosition = 5 % 8; // 5 | |
| // big-endian 순서로 확인: (7 - bitPosition) | |
| boolean extractedBit = ((bitmapData[byteIndex] >> (7 - bitPosition)) & 1) == 1; | |
| assertThat(extractedBit).isTrue(); | |
| } | |
| @Test | |
| @DisplayName("잘못된 오프셋 값에 대한 예외 처리 테스트") | |
| public void testInvalidOffset() { | |
| Long discussionId = 100L; | |
| LocalDateTime dateTime = LocalDateTime.now(); | |
| bitmapService.initializeBitmap(discussionId, dateTime); | |
| assertThatThrownBy(() -> | |
| bitmapService.setBitValue(discussionId, dateTime, -1, true)) | |
| .isInstanceOf(IllegalArgumentException.class); | |
| assertThatThrownBy(() -> | |
| bitmapService.setBitValue(discussionId, dateTime, 16, true)) | |
| .isInstanceOf(IllegalArgumentException.class); | |
| } | |
| @Test | |
| @DisplayName("존재하지 않는 비트맵에 대한 예외 처리 테스트") | |
| public void testNonExistentBitmap() { | |
| Long discussionId = 999L; | |
| LocalDateTime dateTime = LocalDateTime.now(); | |
| assertThatThrownBy(() -> | |
| bitmapService.getBitValue(discussionId, dateTime, 0)) | |
| .isInstanceOf(IllegalStateException.class); | |
| } |
| public Boolean getBitValue(Long discussionId, LocalDateTime dateTime, long bitOffset) { | ||
| long minuteKey = convertToMinuteKey(dateTime); | ||
| String redisKey = buildRedisKey(discussionId, minuteKey); | ||
| return redisTemplate.opsForValue().getBit(redisKey, bitOffset); | ||
| } |
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.
🛠️ Refactor suggestion
Add validation for bitOffset range.
Similar to setBitValue, validate that bitOffset is within the valid range.
public Boolean getBitValue(Long discussionId, LocalDateTime dateTime, long bitOffset) {
+ if (bitOffset < 0 || bitOffset >= BITMAP_SIZE_BYTES * 8) {
+ throw new IllegalArgumentException("bitOffset must be between 0 and " +
+ (BITMAP_SIZE_BYTES * 8 - 1));
+ }
long minuteKey = convertToMinuteKey(dateTime);
String redisKey = buildRedisKey(discussionId, minuteKey);
return redisTemplate.opsForValue().getBit(redisKey, bitOffset);
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| public Boolean getBitValue(Long discussionId, LocalDateTime dateTime, long bitOffset) { | |
| long minuteKey = convertToMinuteKey(dateTime); | |
| String redisKey = buildRedisKey(discussionId, minuteKey); | |
| return redisTemplate.opsForValue().getBit(redisKey, bitOffset); | |
| } | |
| public Boolean getBitValue(Long discussionId, LocalDateTime dateTime, long bitOffset) { | |
| if (bitOffset < 0 || bitOffset >= BITMAP_SIZE_BYTES * 8) { | |
| throw new IllegalArgumentException("bitOffset must be between 0 and " + | |
| (BITMAP_SIZE_BYTES * 8 - 1)); | |
| } | |
| long minuteKey = convertToMinuteKey(dateTime); | |
| String redisKey = buildRedisKey(discussionId, minuteKey); | |
| return redisTemplate.opsForValue().getBit(redisKey, bitOffset); | |
| } |
| public Boolean setBitValue(Long discussionId, LocalDateTime dateTime, long bitOffset, | ||
| boolean value) { | ||
| long minuteKey = convertToMinuteKey(dateTime); | ||
| String redisKey = buildRedisKey(discussionId, minuteKey); | ||
| return redisTemplate.opsForValue().setBit(redisKey, bitOffset, value); | ||
| } |
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.
🛠️ Refactor suggestion
Add validation for bitOffset range.
Since this is a 16-bit bitmap, bitOffset should be between 0 and 15.
public Boolean setBitValue(Long discussionId, LocalDateTime dateTime, long bitOffset,
boolean value) {
+ if (bitOffset < 0 || bitOffset >= BITMAP_SIZE_BYTES * 8) {
+ throw new IllegalArgumentException("bitOffset must be between 0 and " +
+ (BITMAP_SIZE_BYTES * 8 - 1));
+ }
long minuteKey = convertToMinuteKey(dateTime);
String redisKey = buildRedisKey(discussionId, minuteKey);
return redisTemplate.opsForValue().setBit(redisKey, bitOffset, value);
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| public Boolean setBitValue(Long discussionId, LocalDateTime dateTime, long bitOffset, | |
| boolean value) { | |
| long minuteKey = convertToMinuteKey(dateTime); | |
| String redisKey = buildRedisKey(discussionId, minuteKey); | |
| return redisTemplate.opsForValue().setBit(redisKey, bitOffset, value); | |
| } | |
| public Boolean setBitValue(Long discussionId, LocalDateTime dateTime, long bitOffset, | |
| boolean value) { | |
| if (bitOffset < 0 || bitOffset >= BITMAP_SIZE_BYTES * 8) { | |
| throw new IllegalArgumentException("bitOffset must be between 0 and " + | |
| (BITMAP_SIZE_BYTES * 8 - 1)); | |
| } | |
| long minuteKey = convertToMinuteKey(dateTime); | |
| String redisKey = buildRedisKey(discussionId, minuteKey); | |
| return redisTemplate.opsForValue().setBit(redisKey, bitOffset, value); | |
| } |
| * LocalDateTime을 분 단위의 long 값(에포크 기준 분 값)으로 변환. | ||
| */ | ||
| private long convertToMinuteKey(LocalDateTime dateTime) { | ||
| return dateTime.toEpochSecond(ZoneOffset.UTC) / 60; |
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.
p3: 서버 시간이 한국 시간대라서 한국 시간대로 해야 할 거 같습니다.!
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.
반영하여 수정했습니다
| import org.springframework.data.redis.core.RedisTemplate; | ||
|
|
||
| @SpringBootTest | ||
| public class RedisTemplateTest { |
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.
p3: 삭제, 업데이트 테스트 코드도 있으면 좋을 거 같습니다!
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.
추가했습니다
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.
Actionable comments posted: 1
🧹 Nitpick comments (3)
backend/src/main/java/endolphin/backend/global/redis/DiscussionBitmapService.java (3)
45-46: ExtractbyteSizeinto a constantConsider defining a constant for the bitmap size instead of using the hardcoded value
2. This improves code readability and makes future adjustments easier.Apply this diff:
+ private static final int BITMAP_SIZE_BYTES = 2; public void initializeBitmap(Long discussionId, LocalDateTime dateTime) { try { - int byteSize = 2; + int byteSize = BITMAP_SIZE_BYTES;
49-50: Set an expiration for the Redis keysThe TODO comment suggests setting an expiration time. It's advisable to define a TTL (Time To Live) for the Redis keys to prevent unused data from persisting indefinitely, which can help manage memory usage effectively.
105-127: Efficiently delete discussion bitmaps using SCANThe implementation correctly uses SCAN with a pattern to find and delete bitmap keys related to the
discussionId. This approach is effective; however, monitor the performance impact if the number of keys is large. If necessary, consider alternative strategies like using key tags or maintaining an index of keys to improve performance.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
backend/src/main/java/endolphin/backend/global/redis/DiscussionBitmapService.java(1 hunks)backend/src/test/java/endolphin/backend/global/redis/DiscussionBitmapServiceTest.java(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- backend/src/test/java/endolphin/backend/global/redis/DiscussionBitmapServiceTest.java
🔇 Additional comments (3)
backend/src/main/java/endolphin/backend/global/redis/DiscussionBitmapService.java (3)
34-34: Verify that usingZoneOffset.ofHours(9)aligns with your application's timezoneThe method
convertToMinuteKeyusesZoneOffset.ofHours(9)(Korea Standard Time) when convertingLocalDateTimeto epoch seconds. Please ensure that this time zone offset matches your application's expected time zone and the server's configured time zone to prevent any potential time-related issues.
66-71: Add validation forbitOffsetrange insetBitValueThe method lacks validation for the
bitOffsetparameter. To ensure correct operation and prevent errors, validate thatbitOffsetis within the valid range (0 to 15) before proceeding.
81-85: Add validation forbitOffsetrange ingetBitValueSimilarly to
setBitValue, add validation forbitOffsetingetBitValueto ensure it's within the valid range (0 to 15), preventing potential out-of-bounds access.
| } catch (RedisSystemException e) { | ||
| //TODO: 예외 처리 | ||
| throw e; | ||
| } |
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.
Implement proper exception handling
Currently, the catch block rethrows the exception without additional handling. Consider adding logging or custom exception handling to provide more context and facilitate debugging when an error occurs.
kwon204
left a comment
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.
고생하셨습니다.
#️⃣ 연관된 이슈>
📝 작업 내용> 이번 PR에서 작업한 내용을 간략히 설명해주세요(이미지 첨부 가능)
🙏 여기는 꼭 봐주세요! > 리뷰어가 특별히 봐주었으면 하는 부분이 있다면 작성해주세요
Summary by CodeRabbit
New Features
Tests
DiscussionBitmapServiceandRedisTemplateto verify the correctness and reliability of the new data handling capabilities.Chores