1. getPopularKeywordsWithScores(int topN)
public Set<ZSetOperations.TypedTuple<String>> getPopularKeywordsWithScores(int topN) {
return stringRedisTemplate.opsForZSet().reverseRangeWithScores(POPULAR_KEYWORD, 0, topN - 1);
}
- 역할: Redis에 저장된 인기 검색어와 그에 해당하는 점수(검색 횟수 등)를 함께 조회하는 메서드예요.
- 리턴 타입:
Set<ZSetOperations.TypedTuple<String>>
TypedTuple<String>은 Redis의 Sorted Set(ZSet)에서 한 원소의 값과 점수를 함께 담는 객체입니다.
- 예를 들어, ("카페", 150), ("도서관", 100) 이런 식으로 값(검색어)과 점수(검색 횟수)가 같이 들어있어요.
- 사용한 Redis 명령어:
reverseRangeWithScores
- Redis Sorted Set에서 점수가 높은 순서대로 (
reverse) 범위 내 요소와 점수를 조회합니다.
- 여기서는
0부터 topN - 1까지, 즉 상위 topN개의 인기 검색어를 가져오는 거죠.
2. getPopularKeywordResponses(int topN)
public List<PopularKeywordResponse> getPopularKeywordResponses(int topN) {
Set<ZSetOperations.TypedTuple<String>> tuples = getPopularKeywordsWithScores(topN);
List<PopularKeywordResponse> result = new ArrayList<>();
int rank = 1;
for (ZSetOperations.TypedTuple<String> tuple : tuples) {
result.add(new PopularKeywordResponse(rank++, tuple.getValue()));
}
return result;
}
- 역할:
getPopularKeywordsWithScores()에서 가져온 값과 점수 데이터에서 점수는 제외하고, 랭킹(순위)과 검색어 값만을 포함한 DTO 리스트로 변환하는 작업을 합니다.
- 즉, 클라이언트에 보여주기 좋은 형태로 가공하는 역할이죠.
- 구체적인 동작:
getPopularKeywordsWithScores(topN) 호출해서, 인기 검색어와 점수를 같이 받음.
- 빈 리스트
result 생성.
- 순위를 나타내는
rank 변수 1로 초기화.
tuples를 반복하면서:
- 각 원소에서
tuple.getValue()로 검색어를 꺼내고,
rank++로 순위를 붙이고,
PopularKeywordResponse DTO를 만들어 리스트에 추가.
- 최종적으로 순위가 붙은 DTO 리스트 반환.
- 왜 점수는 제외하나?
- 점수(검색 횟수 등)는 내부 로직이나 통계용으로 중요하지만, API 클라이언트가 순위만 알면 충분한 경우가 많아요.
- 만약 점수를 보여줘야 한다면 DTO에 점수 필드를 추가해서 같이 보낼 수도 있습니다.
정리하면
| 메서드 |
역할 |
반환값 |
비고 |
getPopularKeywordsWithScores |
Redis에서 인기 검색어 + 점수를 원본 그대로 조회 |
Set<TypedTuple<String>> |
점수까지 함께 가져옴 |
getPopularKeywordResponses |
원본 데이터를 순위 붙인 DTO 리스트로 변환 |
List<PopularKeywordResponse> |
클라이언트 응답에 맞춰 가공 |
추가 팁
- DTO에 점수까지 포함하고 싶으면
PopularKeywordResponse에 double score 필드를 추가해도 좋아요.
- 랭킹을 붙이는 작업을 이 메서드 안에 두면 컨트롤러나 클라이언트에서 별도 처리하지 않아도 돼서 편리합니다.
- 반대로, 만약 다른 API에서 점수 정보가 필요하면
getPopularKeywordsWithScores()를 직접 호출해 사용하는 것도 유용합니다.