-
Notifications
You must be signed in to change notification settings - Fork 1
feat: Redisson 및 비관적 락을 통한 데이터 정합성 향상 / #121 #122
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
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
d3ac619
test/#redis
kswdot 6591dc4
test/#redis
kswdot efcc8e2
build: redisson 의존성 추가
JayongLee 0791d6a
feat: Redisson을 적용한 스레드 락 설정
JayongLee 8f802e9
refactor: 기존 출금 및 송금 관련 메서드에 Redisson 및 비관적 락 적
JayongLee 18ba70f
test: Redisson 및 비관적 락 관련 테스트
JayongLee 3b1830c
refactor: Redis 장애시 fallback 적
JayongLee a3bcd4e
refactor: @ConfigurationPropertiesScan 추가
JayongLee cfa2e96
docs: redis 설정 변수화
JayongLee e601ae2
test: 분산 락 및 전역 락 적용으로 인한 테스트 코드 변경
JayongLee 8dbbbdf
refactor: PR Review 반영
JayongLee 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
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
29 changes: 29 additions & 0 deletions
29
src/main/java/org/creditto/core_banking/domain/account/service/AccountLockProperties.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,29 @@ | ||
| package org.creditto.core_banking.domain.account.service; | ||
|
|
||
| import org.springframework.boot.context.properties.ConfigurationProperties; | ||
|
|
||
| @ConfigurationProperties(prefix = "core.account-lock") | ||
| public class AccountLockProperties { | ||
|
|
||
| private final long waitMillis; | ||
| private final long leaseMillis; | ||
| private final String accountLockPrefix; | ||
|
|
||
| public AccountLockProperties(long waitMillis, long leaseMillis, String accountLockPrefix) { | ||
| this.waitMillis = waitMillis; | ||
| this.leaseMillis = leaseMillis; | ||
| this.accountLockPrefix = accountLockPrefix; | ||
| } | ||
|
|
||
| public long getWaitMillis() { | ||
| return waitMillis; | ||
| } | ||
|
|
||
| public long getLeaseMillis() { | ||
| return leaseMillis; | ||
| } | ||
|
|
||
| public String getAccountLockPrefix() { | ||
| return accountLockPrefix; | ||
| } | ||
| } |
92 changes: 92 additions & 0 deletions
92
src/main/java/org/creditto/core_banking/domain/account/service/AccountLockService.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,92 @@ | ||
| package org.creditto.core_banking.domain.account.service; | ||
|
|
||
| import java.util.concurrent.TimeUnit; | ||
|
|
||
| import lombok.RequiredArgsConstructor; | ||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.creditto.core_banking.global.response.error.ErrorBaseCode; | ||
| import org.creditto.core_banking.global.response.exception.CustomBaseException; | ||
| import org.redisson.RedissonShutdownException; | ||
| import org.redisson.api.RLock; | ||
| import org.redisson.api.RedissonClient; | ||
| import org.springframework.stereotype.Service; | ||
|
|
||
| @Slf4j | ||
| @Service | ||
| @RequiredArgsConstructor | ||
| public class AccountLockService { | ||
|
|
||
| private final RedissonClient redissonClient; | ||
| private final AccountLockProperties accountLockProperties; | ||
|
|
||
| public <T> T executeWithLock(Long accountId, LockCallback<T> callback) { | ||
| RLock lock = redissonClient.getLock(accountLockProperties.getAccountLockPrefix() + accountId); | ||
| boolean redisLockAcquired = false; | ||
| boolean redisAvailable = true; | ||
|
|
||
| try { | ||
| redisLockAcquired = lock.tryLock( | ||
| accountLockProperties.getWaitMillis(), | ||
| accountLockProperties.getLeaseMillis(), | ||
| TimeUnit.MILLISECONDS | ||
| ); | ||
| } catch (RedissonShutdownException redisException) { | ||
| redisAvailable = false; | ||
| log.warn("Redis lock 불가, fallback 전략을 사용합니다. accountId={}, reason={}", accountId, redisException.getMessage()); | ||
| } catch (InterruptedException e) { | ||
| Thread.currentThread().interrupt(); | ||
| throw new CustomBaseException(ErrorBaseCode.ACCOUNT_LOCK_INTERRUPTED); | ||
| } | ||
|
|
||
| try { | ||
| if (!redisAvailable) { | ||
| // Redis 사용 불가 & DB 분산락만 적용 | ||
| return callback.invokeFallback(); | ||
| } | ||
|
|
||
| if (!redisLockAcquired) { | ||
| // Lock 획득 실패 | ||
| throw new CustomBaseException(ErrorBaseCode.ACCOUNT_LOCK_TIMEOUT); | ||
| } | ||
|
|
||
| return callback.invoke(); | ||
|
|
||
| } catch (InterruptedException e) { | ||
| // Interrupt 관련 에러 | ||
| Thread.currentThread().interrupt(); | ||
| throw new CustomBaseException(ErrorBaseCode.ACCOUNT_LOCK_INTERRUPTED); | ||
| } finally { | ||
| if (redisLockAcquired && lock.isHeldByCurrentThread()) { | ||
| try { | ||
| lock.unlock(); | ||
| } catch (RuntimeException unlockException) { | ||
| log.warn("Redis lock 해제 실패. accountId={}, reason={}", accountId, unlockException.getMessage()); | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| public void executeWithLock(Long accountId, Runnable runnable) { | ||
| executeWithLock(accountId, new LockCallback<Void>() { | ||
| @Override | ||
| public Void invoke() { | ||
| runnable.run(); | ||
| return null; | ||
| } | ||
|
|
||
| @Override | ||
| public Void invokeFallback() { | ||
| runnable.run(); | ||
| return null; | ||
| } | ||
| }); | ||
| } | ||
|
|
||
| public interface LockCallback<T> { | ||
| T invoke() throws InterruptedException; | ||
|
|
||
| default T invokeFallback() throws InterruptedException { | ||
| return invoke(); | ||
| } | ||
| } | ||
| } |
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
28 changes: 28 additions & 0 deletions
28
src/main/java/org/creditto/core_banking/global/config/RedisConfig.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,28 @@ | ||
| package org.creditto.core_banking.global.config; | ||
|
|
||
| import org.springframework.context.annotation.Bean; | ||
| import org.springframework.context.annotation.Configuration; | ||
| import org.springframework.data.redis.connection.RedisConnectionFactory; | ||
| import org.springframework.data.redis.core.RedisTemplate; | ||
| import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; | ||
| import org.springframework.data.redis.serializer.StringRedisSerializer; | ||
|
|
||
| @Configuration | ||
| public class RedisConfig { | ||
|
|
||
| @Bean | ||
| public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) { | ||
| RedisTemplate<String, Object> template = new RedisTemplate<>(); | ||
| template.setConnectionFactory(connectionFactory); | ||
|
|
||
| // key:value | ||
| template.setKeySerializer(new StringRedisSerializer()); | ||
| template.setValueSerializer(new GenericJackson2JsonRedisSerializer()); | ||
|
|
||
| // hash key:value | ||
| template.setHashKeySerializer(new StringRedisSerializer()); | ||
| template.setHashValueSerializer((new GenericJackson2JsonRedisSerializer())); | ||
|
|
||
| return template; | ||
| } | ||
| } |
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
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.
현재
execute메서드에@Transactional이 적용되어 있어 메서드 시작 시점에 트랜잭션이 시작됩니다. 하지만 이 트랜잭션 내에서exchangeService.exchange()(88라인)를 통해 외부 네트워크 호출이 발생하고 있습니다.네트워크 호출과 같이 오래 걸릴 수 있는 작업을 트랜잭션 내에서 수행하는 것은 다음과 같은 이유로 안티패턴으로 간주됩니다.
트랜잭션의 범위를 최소화하도록 리팩토링하는 것을 권장합니다. 트랜잭션은 잔액 확인, 계좌 업데이트, 송금 및 거래 내역 저장 등 원자적으로 실행되어야 하는 최종 작업만 감싸야 합니다.
아래와 같은 리팩토링을 제안합니다.
execute메서드에서@Transactional애노테이션을 제거합니다.processRemittanceTransaction과 같은 새로운 private 또는 protected 메서드를 만들고@Transactional을 적용합니다.execute메서드에서 외부 호출이 완료된 후 이 새로운 트랜잭션 메서드를 호출합니다.이렇게 변경하면 데이터베이스 리소스를 더 빨리 해제하여 애플리케이션의 성능과 안정성을 향상시킬 수 있습니다.