-
Notifications
You must be signed in to change notification settings - Fork 1
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
#346 [feat] 모임명 중복 처리 분산락 적용 #359
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
3f7dd05
#346 [feat] 중복 체크 관련 setnx 처리
sohyundoh 7a05a38
#346 [feat] 로깅 라이브러리 삭제
sohyundoh 29a153c
#346 [test] 테스트 코드 수정
sohyundoh f6c159b
#346 [feat] 분산락 및 트랜잭션 격리 적용
sohyundoh 49181a1
#346 [feat] 모임 정보 수정 적용 & Transactional 어노테이션 삭제
sohyundoh 19c3459
#346 [feat] Lock key에서 signature 삭제
sohyundoh d77a597
#346 [refactor] 코드리뷰 반영
sohyundoh 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 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
90 changes: 90 additions & 0 deletions
90
module-api/src/test/java/com/mile/cocurrency/UniqueNameLockTest.java
This file contains 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,90 @@ | ||
package com.mile.cocurrency; | ||
|
||
import com.fasterxml.jackson.databind.ObjectMapper; | ||
import com.mile.authentication.UserAuthentication; | ||
import com.mile.moim.service.dto.MoimCreateRequest; | ||
import org.junit.jupiter.api.DisplayName; | ||
import org.junit.jupiter.api.Test; | ||
import org.springframework.beans.factory.annotation.Autowired; | ||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; | ||
import org.springframework.boot.test.context.SpringBootTest; | ||
import org.springframework.http.HttpStatus; | ||
import org.springframework.http.MediaType; | ||
import org.springframework.test.web.servlet.MockMvc; | ||
import org.springframework.test.web.servlet.MvcResult; | ||
|
||
import java.util.ArrayList; | ||
import java.util.List; | ||
import java.util.concurrent.CountDownLatch; | ||
import java.util.concurrent.ExecutorService; | ||
import java.util.concurrent.Executors; | ||
|
||
import static org.assertj.core.api.AssertionsForClassTypes.assertThat; | ||
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.authentication; | ||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; | ||
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; | ||
|
||
@SpringBootTest | ||
@AutoConfigureMockMvc | ||
public class UniqueNameLockTest { | ||
@Autowired | ||
private MockMvc mockMvc; | ||
@Autowired | ||
private ObjectMapper objectMapper; | ||
|
||
|
||
@Test | ||
@DisplayName("중복 요청에 대한 Lock으로 인해 동시에 같은 제목으로 요청을 보내면 400 에러를 반환한다.") | ||
public void uniqueMoimNameTest() throws Exception { | ||
// given | ||
int numberOfThread = 4; | ||
ExecutorService executorService = Executors.newFixedThreadPool(numberOfThread); | ||
CountDownLatch latch = new CountDownLatch(numberOfThread); | ||
|
||
MoimCreateRequest bodyDto = new | ||
MoimCreateRequest("이정해봅시다", "string", false, "string", "string", "string", "string", "str", "string"); | ||
|
||
String body = objectMapper.writeValueAsString(bodyDto); | ||
|
||
// when | ||
List<MvcResult> results = new ArrayList<>(); | ||
UserAuthentication testUser = new UserAuthentication(1L, null, null); | ||
|
||
for (int i = 0; i < numberOfThread; i++) { | ||
executorService.submit(() -> { | ||
try { | ||
MvcResult result = mockMvc.perform( | ||
post("/api/moim") | ||
.contentType(MediaType.APPLICATION_JSON) | ||
.content(body) | ||
.with(authentication(testUser)) | ||
) | ||
.andDo(print()) | ||
.andReturn(); | ||
synchronized (results) { | ||
results.add(result); | ||
} | ||
} catch (Exception e) { | ||
throw new RuntimeException(e); | ||
} finally { | ||
latch.countDown(); | ||
} | ||
}); | ||
} | ||
latch.await(); | ||
|
||
// then | ||
int count200 = 0; | ||
int count400 = 0; | ||
for (MvcResult mvcResult : results) { | ||
if (mvcResult.getResponse().getStatus() == HttpStatus.OK.value()) count200++; | ||
else if (mvcResult.getResponse().getStatus() == HttpStatus.BAD_REQUEST.value()) count400++; | ||
} | ||
System.out.println(count400); | ||
|
||
assertThat(count200).isEqualTo(1); | ||
assertThat(count400).isEqualTo(numberOfThread - 1); | ||
} | ||
|
||
} | ||
|
This file contains 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 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 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
15 changes: 15 additions & 0 deletions
15
module-domain/src/main/java/com/mile/moim/service/lock/AopForTransaction.java
This file contains 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,15 @@ | ||
package com.mile.moim.service.lock; | ||
|
||
import org.aspectj.lang.ProceedingJoinPoint; | ||
import org.springframework.stereotype.Component; | ||
import org.springframework.transaction.annotation.Propagation; | ||
import org.springframework.transaction.annotation.Transactional; | ||
|
||
@Component | ||
public class AopForTransaction { | ||
|
||
@Transactional(propagation = Propagation.REQUIRES_NEW) | ||
public Object proceed(final ProceedingJoinPoint joinPoint) throws Throwable { | ||
return joinPoint.proceed(); | ||
} | ||
} |
11 changes: 11 additions & 0 deletions
11
module-domain/src/main/java/com/mile/moim/service/lock/AtomicValidateUniqueMoimName.java
This file contains 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,11 @@ | ||
package com.mile.moim.service.lock; | ||
|
||
import java.lang.annotation.ElementType; | ||
import java.lang.annotation.Retention; | ||
import java.lang.annotation.RetentionPolicy; | ||
import java.lang.annotation.Target; | ||
|
||
@Target({ElementType.METHOD}) | ||
@Retention(RetentionPolicy.RUNTIME) | ||
public @interface AtomicValidateUniqueMoimName { | ||
} |
46 changes: 46 additions & 0 deletions
46
module-domain/src/main/java/com/mile/moim/service/lock/MoimNameRequestAspect.java
This file contains 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,46 @@ | ||
package com.mile.moim.service.lock; | ||
|
||
import com.mile.exception.message.ErrorMessage; | ||
import com.mile.exception.model.MileException; | ||
import lombok.RequiredArgsConstructor; | ||
import org.aspectj.lang.ProceedingJoinPoint; | ||
import org.aspectj.lang.annotation.Around; | ||
import org.aspectj.lang.annotation.Aspect; | ||
import org.aspectj.lang.annotation.Pointcut; | ||
import org.redisson.api.RLock; | ||
import org.redisson.api.RedissonClient; | ||
import org.springframework.stereotype.Component; | ||
|
||
import java.util.concurrent.TimeUnit; | ||
|
||
@Aspect | ||
@RequiredArgsConstructor | ||
@Component | ||
public class MoimNameRequestAspect { | ||
|
||
private final RedissonClient redissonClient; | ||
private final static String MOIM_NAME_LOCK = "MOIM_NAME_LOCK : "; | ||
private final AopForTransaction aopForTransaction; | ||
|
||
@Pointcut("@annotation(com.mile.moim.service.lock.AtomicValidateUniqueMoimName)") | ||
public void uniqueMoimNameCut() { | ||
} | ||
|
||
@Around("uniqueMoimNameCut()") | ||
public Object validateUniqueName(final ProceedingJoinPoint joinPoint) throws Throwable { | ||
final RLock lock = redissonClient.getLock(MOIM_NAME_LOCK); | ||
try { | ||
checkAvailability(lock.tryLock(3, 4, TimeUnit.SECONDS)); | ||
return aopForTransaction.proceed(joinPoint); | ||
} catch (InterruptedException e) { | ||
throw new RuntimeException(e); | ||
} finally { | ||
lock.unlock(); | ||
} | ||
} | ||
|
||
public void checkAvailability(final Boolean available) { | ||
if (!available) throw new MileException(ErrorMessage.TIME_OUT_EXCEPTION); | ||
} | ||
|
||
} |
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.
P5) (제가 이해한 바에 따르면).. 분산락은 현재 메서드 별로 생성되고 있는데, 중복 확인을 수행하는 메서드가 여러 개 있다면 락의 효과가 감소하지 않나요!? 예를 들어서 두 유저가 동시에 각각 같은 이름으로 글모임 수정/글모임 생성을 요청한다고 가정해 본다면. 한 유저는 글모임 수정을 할 때 validateMoimName 메서드가 호출되고, 한 유저는 글모임 생성할 때 동시에 checkMoimNameUnique가 호출된다면, 락은 각각 다른 이름의 키로 별도이기 때문에 분산락의 효과가 없지 않는지 궁금합니닷...
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.
P5) 그래서 제가 생각했을 땐 validateMoimName과 checkMoimNameUnique에서 이뤄지고 있는 중복확인 로직을 단일 메서드로 통일해야 분산락의 효과를 볼 수 있지 않나 싶었는데요..! 그렇게 되면 createMoim이나 modifyMoiminformation에 @AtomicValidateUniqueMoimName 어노테이션을 붙일 필요 없이, 중복확인용 메서드에만 어노테이션을 붙여서 모든 중복확인이 동일한 락을 사용하게 하면 되지 않을까 싶습니다
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.
흠 이 부분에서 제가 실수한 부분이 있었습니다! 모든 메서드에서 락을 걸고 joinpoint에서 signature로 락을 걸면 안됐는데요! 이 부분 수정하겠습니다! :) 감사합니다!
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.
중복 체크 메서드에만 락을 걸어주는 것은 맞지 않습니다!
그 이유는 자원의 생성과 중복 체크가 동시에 일어날 수 있기 때문에 분산락을 적용한 것인데, 중복 체크만 락을 걸어줄 경우 그 사이에 이름의 자원이 생성되었을 때에는 원자성을 보장하지 못하기 때문입니다!
그래서 어노테이션을 통해서 락의 범위를 정해준 것입니다!