-
Notifications
You must be signed in to change notification settings - Fork 37
[4주차] RateLimit 적용, 테스트코드 작성 #86
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
soyoungcareer
wants to merge
6
commits into
hanghae-skillup:soyoungcareer
Choose a base branch
from
soyoungcareer:week4
base: soyoungcareer
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
6 commits
Select commit
Hold shift + click to select a range
f5c5093
refactor: 3주차 피드백 반영
soyoungcareer 7d298e4
fea: Guava RateLimit 적용
soyoungcareer 02571d6
fix: 예매 성공한 경우에만 5분 제한 적용
soyoungcareer 6b9bc94
feat: 테스트코드 추가
soyoungcareer e668361
feat: Redisson RateLimit 적용
soyoungcareer ec2db4e
feat: Jacoco 추가
soyoungcareer 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
36 changes: 36 additions & 0 deletions
36
cinema-adapter/src/main/java/com/cinema/adapter/config/RateLimiterConfig.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,36 @@ | ||
| package com.cinema.adapter.config; | ||
|
|
||
| import com.google.common.util.concurrent.RateLimiter; | ||
| import org.redisson.api.RRateLimiter; | ||
| import org.redisson.api.RateIntervalUnit; | ||
| import org.redisson.api.RateType; | ||
| import org.redisson.api.RedissonClient; | ||
| import org.springframework.context.annotation.Bean; | ||
| import org.springframework.context.annotation.Configuration; | ||
|
|
||
| @Configuration | ||
| public class RateLimiterConfig { | ||
|
|
||
| // Google Guava | ||
| /*@Bean | ||
| public RateLimiter rateLimiter() { | ||
| return RateLimiter.create(50.0 / 60.0); // 1분당 50회 | ||
| }*/ | ||
|
|
||
|
|
||
| // Redisson | ||
| private static final String RATE_LIMIT_KEY = "rate_limit:requests"; | ||
|
|
||
| private final RedissonClient redissonClient; | ||
|
|
||
| public RateLimiterConfig(RedissonClient redissonClient) { | ||
| this.redissonClient = redissonClient; | ||
| } | ||
|
|
||
| @Bean | ||
| public RRateLimiter rateLimiter() { | ||
| RRateLimiter rateLimiter = redissonClient.getRateLimiter(RATE_LIMIT_KEY); | ||
| rateLimiter.trySetRate(RateType.OVERALL, 50, 1, RateIntervalUnit.MINUTES); // 1분당 50회 | ||
| return rateLimiter; | ||
| } | ||
| } |
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
82 changes: 82 additions & 0 deletions
82
cinema-adapter/src/main/java/com/cinema/adapter/interceptor/RateLimitingInterceptor.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,82 @@ | ||
| package com.cinema.adapter.interceptor; | ||
|
|
||
| import com.google.common.util.concurrent.RateLimiter; | ||
| import jakarta.servlet.http.HttpServletRequest; | ||
| import jakarta.servlet.http.HttpServletResponse; | ||
| import lombok.RequiredArgsConstructor; | ||
| import org.redisson.api.RRateLimiter; | ||
| import org.springframework.http.HttpStatus; | ||
| import org.springframework.stereotype.Component; | ||
| import org.springframework.web.servlet.HandlerInterceptor; | ||
|
|
||
| import java.time.Instant; | ||
| import java.time.ZoneId; | ||
| import java.time.format.DateTimeFormatter; | ||
| import java.util.Map; | ||
| import java.util.concurrent.ConcurrentHashMap; | ||
| import java.util.concurrent.TimeUnit; | ||
|
|
||
| @Component | ||
| @RequiredArgsConstructor | ||
| public class RateLimitingInterceptor implements HandlerInterceptor { | ||
|
|
||
| // private final RateLimiter rateLimiter; // Google Guava | ||
| private final RRateLimiter rateLimiter; // Redisson | ||
|
|
||
| private final Map<String, Integer> requestCounts = new ConcurrentHashMap<>(); | ||
| private final Map<String, Long> blockedIps = new ConcurrentHashMap<>(); | ||
|
|
||
| private static final int MAX_REQUESTS = 50; // 1분 내 최대 50회 | ||
| private static final long BLOCK_TIME_MS = 60 * 60 * 1000; // 1시간 차단 | ||
|
|
||
| @Override | ||
| public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { | ||
| String clientIp = request.getRemoteAddr(); | ||
| long currentTime = System.currentTimeMillis(); | ||
|
|
||
| // 1. 조회 API 제한 - 차단된 IP인지 확인 | ||
| if (blockedIps.containsKey(clientIp)) { | ||
| long blockedTime = blockedIps.get(clientIp); | ||
| if (currentTime - blockedTime < BLOCK_TIME_MS) { | ||
| String unblockTime = Instant.ofEpochMilli(blockedTime + BLOCK_TIME_MS) | ||
| .atZone(ZoneId.systemDefault()) | ||
| .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); | ||
|
|
||
| response.setStatus(HttpServletResponse.SC_FORBIDDEN); | ||
| response.getWriter().write("해당 IP는 1시간 동안 요청이 차단되었습니다. 차단 해제 시각: " + unblockTime); | ||
| return false; | ||
| } else { | ||
| blockedIps.remove(clientIp); | ||
| requestCounts.remove(clientIp); | ||
| } | ||
| } | ||
|
|
||
| // 2. 조회 API 제한 - 1분 내 50회 | ||
| if (request.getRequestURI().startsWith("/api/v1/movies") && request.getMethod().equalsIgnoreCase("GET")) { | ||
| requestCounts.put(clientIp, requestCounts.getOrDefault(clientIp, 0) + 1); | ||
| if (requestCounts.get(clientIp) > MAX_REQUESTS) { | ||
| blockedIps.put(clientIp, currentTime); | ||
| response.setStatus(HttpServletResponse.SC_FORBIDDEN); | ||
| response.getWriter().write("너무 많은 요청으로 해당 IP는 요청이 차단되었습니다."); | ||
| return false; | ||
| } | ||
|
|
||
| // 실시간 요청 속도 제한 적용 (RateLimiter) | ||
| // Google Guava | ||
| /*if (!rateLimiter.tryAcquire()) { | ||
| response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value()); | ||
| response.getWriter().write("현재 요청량이 너무 많습니다. 잠시 후 다시 시도해주세요."); | ||
| return false; | ||
| }*/ | ||
|
|
||
| // Redisson | ||
| if (!rateLimiter.tryAcquire(1, TimeUnit.SECONDS)) { | ||
| response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value()); | ||
| response.getWriter().write("현재 요청량이 너무 많습니다. 잠시 후 다시 시도해주세요."); | ||
| return false; | ||
| } | ||
|
Comment on lines
+72
to
+77
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. 클라이언트 ip별로 다르게 rateLimiter 가 존재해야 할듯 합니다. |
||
| } | ||
|
|
||
| return true; | ||
| } | ||
| } | ||
23 changes: 0 additions & 23 deletions
23
cinema-adapter/src/test/java/com/cinema/PessimisticLockTest.java
This file was deleted.
Oops, something went wrong.
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.
동일한 clientIp로 두 개의 요청이 동시에 들어왔다고 가정했을 때, 해당 코드는 정상 실행이 될까요?
동시성에 대해 다시 생각해보셨으면 좋겠습니다!