Skip to content

fix: 광고 랜덤 조회의 반복 단건 조회를 제거해 쿼리 횟수를 줄임 - #449

Merged
dh2906 merged 2 commits into
developfrom
refactor/get-ad-perf
Mar 28, 2026
Merged

fix: 광고 랜덤 조회의 반복 단건 조회를 제거해 쿼리 횟수를 줄임#449
dh2906 merged 2 commits into
developfrom
refactor/get-ad-perf

Conversation

@dh2906

@dh2906 dh2906 commented Mar 28, 2026

Copy link
Copy Markdown
Contributor

🔍 개요

  • 활성화 광고 목록을 조회 후 랜덤으로 id를 뽑고, id를 통해 다시 광고를 조회하는 로직으로 1 + N번 쿼리가 나가게 된다.

🚀 주요 변경 내용

  • 최초로 조회한 광고 목록을 재활용하도록 수정했습니다.

💬 참고 사항


✅ Checklist (완료 조건)

  • 코드 스타일 가이드 준수
  • 테스트 코드 포함됨
  • Reviewers / Assignees / Labels 지정 완료
  • 보안 및 민감 정보 검증 (API 키, 환경 변수, 개인정보 등)

@dh2906 dh2906 self-assigned this Mar 28, 2026
@dh2906 dh2906 added the 리팩토링 리팩터링을 위한 이슈입니다. label Mar 28, 2026
@coderabbitai

coderabbitai Bot commented Mar 28, 2026

Copy link
Copy Markdown
📝 Walkthrough

개요

저장소 메서드 findAllVisibleIds()를 제거하고 getRandomAdvertisements() 메서드를 수정하여 ID 기반 조회 대신 직접 보이는 광고 엔티티를 조회하도록 변경했습니다. ThreadLocalRandom을 사용하고 선택 로직을 개선했습니다.

변경사항

코호트 / 파일 요약
저장소 메서드 제거
src/main/java/gg/agit/konect/domain/advertisement/repository/AdvertisementRepository.java
findAllVisibleIds() 메서드 및 관련 JPQL 쿼리 제거. 보이는 광고 ID만 조회하는 기능 삭제.
서비스 로직 최적화
src/main/java/gg/agit/konect/domain/advertisement/service/AdvertisementService.java
getRandomAdvertisements() 메서드를 직접 엔티티 조회 방식으로 변경. 충분한 광고가 있을 때 리스트 셔플, 부족할 때 반복 선택 로직 유지. Math.random() 대신 ThreadLocalRandom.current().nextInt() 사용.

예상 코드 리뷰 노력

🎯 2 (Simple) | ⏱️ ~12 분

관련 가능 PR

  • fix: 광고 조회 API 통합 #417: 광고 무작위 선택 동작 수정 사항이 동일하게 ID 기반 조회에서 직접 엔티티 선택으로 변경되는 관련 변경사항.

🐰 ID 매핑을 걷어내고
광고 엔티티를 곧바로 담아
ThreadLocal의 주사위를 굴려
무작위 선택은 더 빠르고 밝아 ✨
단순함 속에서 효율을 찾다

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed 제목은 광고 조회 성능 최적화를 통한 쿼리 횟수 감소라는 주요 변경 사항을 명확하게 요약하고 있습니다.
Description check ✅ Passed 설명은 문제 상황(N+1 쿼리 문제), 해결 방안(조회한 광고 목록 재활용), 그리고 체크리스트를 포함하여 변경 사항과 관련된 내용을 충분히 포함하고 있습니다.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch refactor/get-ad-perf

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions

Copy link
Copy Markdown

⚠️ Checkstyle 위반 사항 발견

Checkstyle 검사에서 코딩 컨벤션 위반이 발견되었습니다.

📋 상세 리포트

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In
`@src/main/java/gg/agit/konect/domain/advertisement/service/AdvertisementService.java`:
- Around line 28-51: The getRandomAdvertisements method can throw
IndexOutOfBounds when count is negative; at the start of
AdvertisementService.getRandomAdvertisements validate or clamp count to
non-negative (e.g., if count <= 0 return AdvertisementsResponse.from(List.of())
or set count = Math.max(0, count)) so the subsequent
visibleAdvertisements.size() >= count check and subList(0, count) cannot receive
a negative value; update references to count accordingly before creating
selectedAdvertisements.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 11c02f0f-b6c3-42cb-ad81-34ef90e29dbc

📥 Commits

Reviewing files that changed from the base of the PR and between 6c81e4d and 4225625.

📒 Files selected for processing (2)
  • src/main/java/gg/agit/konect/domain/advertisement/repository/AdvertisementRepository.java
  • src/main/java/gg/agit/konect/domain/advertisement/service/AdvertisementService.java
💤 Files with no reviewable changes (1)
  • src/main/java/gg/agit/konect/domain/advertisement/repository/AdvertisementRepository.java
📜 Review details
🧰 Additional context used
📓 Path-based instructions (2)
src/main/java/**/*.java

⚙️ CodeRabbit configuration file

src/main/java/**/*.java: 아래 원칙으로 리뷰 코멘트를 작성한다.

  • 코멘트는 반드시 한국어로 작성한다.
  • 반드시 수정이 필요한 항목만 코멘트로 남기고, 단순 취향 차이는 지적하지 않는다.
  • 각 코멘트 첫 줄에 심각도를 [LEVEL: high|medium|low] 형식으로 반드시 표기한다.
  • 심각도 기준: high=운영 장애 가능, medium=품질 저하, low=개선 권고.
  • 각 코멘트는 "문제 -> 영향 -> 제안" 순서로 3문장 이내로 간결하게 작성한다.
  • 가능하면 재현 조건 및 실패 시나리오도 포함한다.
  • 제안은 현재 코드베이스(Spring Boot + JPA + Flyway) 패턴과 일치해야 한다.
  • 보안, 트랜잭션 경계, 예외 처리, N+1, 성능 회귀 가능성을 우선 점검한다.
  • 가독성: 변수/메서드 이름이 의도를 바로 드러내는지, 중첩과 메서드 길이가 과도하지 않은지 점검한다.
  • 단순화: 불필요한 추상화, 중복 로직, 과한 방어 코드가 있으면 더 단순한 대안을 제시한다.
  • 확장성: 새 요구사항 추가 시 변경 범위가 최소화되는 구조인지(하드코딩 분기/값 여부 포함) 점검한다.

Files:

  • src/main/java/gg/agit/konect/domain/advertisement/service/AdvertisementService.java
**/*

⚙️ CodeRabbit configuration file

**/*: 공통 리뷰 톤 가이드:

  • 모든 코멘트는 첫 줄에 [LEVEL: ...] 태그를 포함한다.
  • 과장된 표현 없이 사실 기반으로 작성한다.
  • 한 코멘트에는 하나의 이슈만 다룬다.
  • 코드 예시가 필요하면 최소 수정 예시를 제시한다.
  • 가독성/단순화/확장성 이슈를 발견하면 우선순위를 높여 코멘트한다.

Files:

  • src/main/java/gg/agit/konect/domain/advertisement/service/AdvertisementService.java
🔇 Additional comments (1)
src/main/java/gg/agit/konect/domain/advertisement/service/AdvertisementService.java (1)

29-30: N+1 쿼리 문제 해결 확인.

기존 ID 목록 조회 후 반복 단건 조회하던 로직을 제거하고, 최초 조회한 광고 목록을 직접 재활용하여 쿼리 횟수를 1 + N에서 1로 줄였습니다. ThreadLocalRandom 사용과 shuffle 전 방어적 복사도 적절합니다.

Also applies to: 36-50

@dh2906
dh2906 merged commit 7d60fe3 into develop Mar 28, 2026
3 checks passed
@dh2906
dh2906 deleted the refactor/get-ad-perf branch March 28, 2026 03:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

리팩토링 리팩터링을 위한 이슈입니다.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant