-
Notifications
You must be signed in to change notification settings - Fork 0
[BE] 동시성 수정 및 Redis 캐시 사용 #324
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
Open
soyun-i
wants to merge
15
commits into
develop
Choose a base branch
from
be/feat/317
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
83f5f3a
✨ feat: 락 범위 축소 및 Redis 활용 1차
soyun-i 42759da
✨ feat: 락 범위 축소 및 Redis 활용 2차
soyun-i b3385e6
✨ feat: 락 범위 축소 및 Redis 활용 3차
soyun-i 764fc55
🛠️ refactor: 주석처리 제거 및 컨벤션 확인
soyun-i 569f0e0
🛠️ refactor: stockService 삭제 및 락 재시도 로직 추가
soyun-i 8add1ce
🛠️ refactor: 필요없는 메서드 삭제
soyun-i 33373ee
🛠️ refactor: redisson으로 통일 및 메서드 private으로 전환
soyun-i f36d109
🛠️ refactor: 주석 제거
soyun-i f8a12cd
🛠️ refactor: 락 범위 수정
soyun-i bf6af20
🛠️ refactor: 락 범위 수정
soyun-i 556d22e
🛠️ refactor: 락 범위 수정
soyun-i 71a2868
🛠️ refactor: 락 범위 수정
soyun-i 36686fc
🛠️ refactor: 락 범위 수정
soyun-i 9dfc3d6
🛠️ refactor: 락 전체적인 수정
soyun-i 77cf9de
🛠️ refactor: 테스트코드 추가 및 수정
soyun-i 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
37 changes: 37 additions & 0 deletions
37
backend/JiShop/src/main/java/com/jishop/config/AsyncConfig.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,37 @@ | ||
| package com.jishop.config; | ||
|
|
||
| import org.springframework.context.annotation.Bean; | ||
| import org.springframework.context.annotation.Configuration; | ||
| import org.springframework.scheduling.annotation.EnableAsync; | ||
| import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; | ||
|
|
||
| import java.util.concurrent.Executor; | ||
|
|
||
| @EnableAsync | ||
| @Configuration | ||
| public class AsyncConfig { | ||
|
|
||
| @Bean(name = "stockTaskExecutor") | ||
| public Executor stockTaskExecutor() { | ||
| ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); | ||
| executor.setCorePoolSize(7); //기본 스레드 수 | ||
| executor.setMaxPoolSize(15); //최대 스레드 수 | ||
| executor.setQueueCapacity(100); //큐 용량 | ||
| executor.setThreadNamePrefix("stock-async-"); | ||
| executor.initialize(); | ||
|
|
||
| return executor; | ||
| } | ||
|
|
||
| @Bean(name = "orderTaskExecutor") | ||
| public Executor orderTaskExecutor() { | ||
| ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); | ||
| executor.setCorePoolSize(3); | ||
| executor.setMaxPoolSize(5); | ||
| executor.setQueueCapacity(10); | ||
| executor.setThreadNamePrefix("order-async-"); | ||
| executor.initialize(); | ||
|
|
||
| return executor; | ||
| } | ||
| } |
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
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 |
|---|---|---|
|
|
@@ -3,40 +3,69 @@ | |
| import com.jishop.common.exception.DomainException; | ||
| import com.jishop.common.exception.ErrorType; | ||
| import lombok.RequiredArgsConstructor; | ||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.redisson.api.RLock; | ||
| import org.redisson.api.RedissonClient; | ||
| import org.springframework.stereotype.Service; | ||
|
|
||
| import java.util.List; | ||
| import java.util.concurrent.TimeUnit; | ||
| import java.util.function.Supplier; | ||
|
|
||
| @Slf4j | ||
| @Service | ||
| @RequiredArgsConstructor | ||
| public class DistributedLockService { | ||
|
|
||
| private final RedissonClient redisson; | ||
| private static final long DEFAULT_WAIT_TIME = 5L; | ||
| private static final long DEFAULT_LEASE_TIME = 5L; | ||
| private static final long DEFAULT_WAIT_TIME = 10L; //기다리는 시간 증가 | ||
| private static final long DEFAULT_LEASE_TIME = 15L; // 락 유지 시간 증가 | ||
| private static final int DEFAULT_RETRY_COUNT = 3; | ||
|
|
||
| public <T> T executeWithLock(String lockName, Supplier<T> supplier){ | ||
| return executeWithLock(lockName, DEFAULT_WAIT_TIME, DEFAULT_LEASE_TIME, supplier); | ||
| public <T> T executeWithLock(String lockName, Supplier<T> supplier) { | ||
| return executeWithLock(lockName, DEFAULT_WAIT_TIME, DEFAULT_LEASE_TIME, DEFAULT_RETRY_COUNT, supplier); | ||
| } | ||
|
|
||
| public <T> T executeWithLock(String lockName, long waitTime, long leaseTime, Supplier<T> supplier) { | ||
| public <T> T executeWithLock(String lockName, long waitTime, long leaseTime, int retryCount, Supplier<T> supplier) { | ||
| RLock lock = redisson.getLock(lockName); | ||
| try { | ||
| boolean isLocked = lock.tryLock(waitTime, leaseTime, TimeUnit.SECONDS); | ||
| if (!isLocked) { | ||
| throw new DomainException(ErrorType.LOCK_ACQUISITION_FAILED); | ||
| } | ||
| boolean isLocked = false; | ||
| int attempts = 0; | ||
|
|
||
| while (attempts < retryCount) { | ||
| try { | ||
| log.debug("락 얻기 시도 ({}/{}): {}", attempts + 1, retryCount, lockName); | ||
| isLocked = lock.tryLock(waitTime, leaseTime, TimeUnit.SECONDS); | ||
|
|
||
| if (!isLocked) { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 락 얻기 실패했을경우 별도로 다른 처리가 필요 하지 않을까요? |
||
| log.warn("락 얻기 실패 ({}/{}): {}", attempts + 1, retryCount, lockName); | ||
| attempts++; | ||
| //지수 백오프 적용 | ||
| Thread.sleep(100 * (long) Math.pow(2, attempts)); | ||
| continue; | ||
| } | ||
|
|
||
| log.debug("락 얻기 성공: {}", lockName); | ||
| return supplier.get(); | ||
|
|
||
| } catch (InterruptedException e) { | ||
| Thread.currentThread().interrupt(); | ||
| log.error("락 방해됨: {}", lockName, e); | ||
| throw new DomainException(ErrorType.CONCURRENT_ORDER_PROCESSING); | ||
| } catch (Exception e) { | ||
| log.error("락 처리 중 에러 발생 {}: {}", lockName, e.getMessage(), e); | ||
| throw e; | ||
| } finally { | ||
| lock.unlock(); | ||
| if (isLocked && lock.isHeldByCurrentThread()) { | ||
| try { | ||
| lock.unlock(); | ||
| log.debug("락 해제: {}", lockName); | ||
| } catch (Exception e) { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 락 해제에 실패했을때도 별도의 처리가 있어야하지 않을까요? |
||
| log.error("락 해제 중 에러 발생 {}: {}", lockName, e.getMessage(), e); | ||
| } | ||
| } | ||
| } | ||
| } catch (InterruptedException e) { | ||
| Thread.currentThread().interrupt(); | ||
| throw new DomainException(ErrorType.CONCURRENT_ORDER_PROCESSING); | ||
| } | ||
| // 모든 재시도 후에도 실패한다면 | ||
| throw new DomainException(ErrorType.LOCK_ACQUISITION_FAILED); | ||
| } | ||
| } | ||
| } | ||
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
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
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.
제네릭을 사용하신 이유가 따로 있으신가요?