Skip to content

Commit

Permalink
feat: 제출 관련 분산락 구현 (redis)
Browse files Browse the repository at this point in the history
  • Loading branch information
alstn113 committed Dec 16, 2024
1 parent b977821 commit 820416d
Show file tree
Hide file tree
Showing 11 changed files with 144 additions and 7 deletions.
4 changes: 2 additions & 2 deletions server/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ dependencies {
runtimeOnly 'org.postgresql:postgresql'

// redis
// implementation 'org.springframework.boot:spring-boot-starter-data-redis'
// implementation 'io.lettuce.core:lettuce-core'
implementation 'org.springframework.boot:spring-boot-starter-data-redis'
implementation 'org.springframework.boot:spring-boot-starter-cache'

// lombok
compileOnly 'org.projectlombok:lombok'
Expand Down
7 changes: 7 additions & 0 deletions server/compose.local.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
services:
redis:
container_name: fluffy-redis
image: redis:7.4.1
restart: always
ports:
- '6379:6379'
6 changes: 6 additions & 0 deletions server/compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,9 @@ services:
TZ: Asia/Seoul
SPRING_PROFILES_ACTIVE: prod
restart: always
redis:
container_name: fluffy-redis
image: redis:7.4.1
restart: always
ports:
- '6379:6379'
21 changes: 21 additions & 0 deletions server/src/main/java/com/fluffy/global/cache/LockManager.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package com.fluffy.global.cache;

import java.time.Duration;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class LockManager {

private final RedisTemplate<String, String> redisTemplate;

public Boolean lock(String key) {
return redisTemplate.opsForValue().setIfAbsent(key, "lock", Duration.ofSeconds(3));
}

public Boolean unlock(String key) {
return redisTemplate.delete(key);
}
}
30 changes: 30 additions & 0 deletions server/src/main/java/com/fluffy/global/cache/RedisConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package com.fluffy.global.cache;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;

@Configuration
public class RedisConfig {

@Value("${spring.data.redis.host}")
private String redisHost;

@Value("${spring.data.redis.port}")
private int redisPort;

@Bean
public RedisConnectionFactory redisConnectionFactory() {
return new LettuceConnectionFactory(redisHost, redisPort);
}

@Bean
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory());
return template;
}
}
51 changes: 51 additions & 0 deletions server/src/main/java/com/fluffy/global/cache/RedisLockUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package com.fluffy.global.cache;

import java.util.function.Supplier;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RequiredArgsConstructor
public class RedisLockUtil {

private final LockManager manager;

public <T> T acquireAndRunLock(String key, Supplier<T> block) {
if (key == null || key.isBlank()) {
throw new IllegalArgumentException("[RedisLock] Key cannot be null or empty");
}

if (Boolean.TRUE.equals(acquireLock(key))) {
return proceedWithLock(key, block);
}

throw new IllegalStateException("[RedisLock] Failed to acquire lock for key: " + key);
}

private Boolean acquireLock(String key) {
try {
return manager.lock(key);
} catch (Exception e) {
log.error("[RedisLock] Failed to acquire lock for key: {}", key, e);
return false;
}
}

private <T> T proceedWithLock(String key, Supplier<T> block) {
try {
return block.get();
} finally {
releaseLock(key);
}
}

private void releaseLock(String key) {
try {
manager.unlock(key);
} catch (Exception e) {
log.error("[RedisLock] Failed to release lock for key: {}", key, e);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import com.fluffy.auth.domain.MemberRepository;
import com.fluffy.exam.domain.Exam;
import com.fluffy.exam.domain.ExamRepository;
import com.fluffy.global.cache.RedisLockUtil;
import com.fluffy.global.exception.BadRequestException;
import com.fluffy.submission.application.dto.SubmissionAppRequest;
import com.fluffy.submission.domain.Submission;
Expand All @@ -20,6 +21,7 @@ public class SubmissionService {
private final SubmissionRepository submissionRepository;
private final MemberRepository memberRepository;
private final SubmissionMapper submissionMapper;
private final RedisLockUtil redisLockUtil;

@Transactional
public void submit(SubmissionAppRequest request) {
Expand All @@ -30,13 +32,15 @@ public void submit(SubmissionAppRequest request) {
throw new BadRequestException("시험이 공개되지 않았습니다.");
}

//TODO: 존재하지 않는 것에 대한 동시성 문제 aka 따닥 -> Redis 분산락 고려 ?
//TODO: unique 제약조건 examId, memberId ?
if (submissionRepository.existsByExamIdAndMemberId(exam.getId(), member.getId())) {
throw new BadRequestException("이미 제출한 시험입니다.");
}

Submission submission = submissionMapper.toSubmission(exam, member.getId(), request);
submissionRepository.save(submission);
String key = "submission:%d:%d".formatted(exam.getId(), member.getId());
redisLockUtil.acquireAndRunLock(key, () -> {
Submission submission = submissionMapper.toSubmission(exam, member.getId(), request);
submissionRepository.save(submission);
return null;
});
}
}
6 changes: 6 additions & 0 deletions server/src/main/resources/application-local.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@ spring:
highlight_sql: true
hibernate:
ddl-auto: create-drop
data:
redis:
host: localhost
port: 6379
cache:
type: redis
mail:
host: ${MAIL_HOST}
port: 587
Expand Down
6 changes: 6 additions & 0 deletions server/src/main/resources/application-prod.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@ spring:
highlight_sql: true
hibernate:
ddl-auto: validate
data:
redis:
host: fluffy-redis
port: 6379
cache:
type: redis
mail:
host: ${MAIL_HOST}
port: 587
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ void submit() throws InterruptedException {
try {
submissionService.submit(request);
} catch (RuntimeException e) {
// ignore
e.printStackTrace();
}
});
}
Expand Down
6 changes: 6 additions & 0 deletions server/src/test/resources/application-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,12 @@ spring:
hibernate:
format_sql: true
highlight_sql: true
data:
redis:
host: localhost
port: 6379
cache:
type: redis
mail:
host: smtp.gmail.com
port: 587
Expand Down

0 comments on commit 820416d

Please sign in to comment.