Skip to content

Commit

Permalink
Merge pull request #130 from woowa-techcamp-2024/feature/129-ad-id
Browse files Browse the repository at this point in the history
[fix] 동일 키워드와 동일 id가 오면 동일 광고가 응답되게 수정
  • Loading branch information
hellomatia authored Aug 26, 2024
2 parents ec36611 + 67e8341 commit e139b51
Showing 1 changed file with 15 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import lombok.Getter;
import lombok.Setter;
import org.springframework.web.bind.annotation.PostMapping;
Expand All @@ -18,6 +20,8 @@
public class AdvertisementController {

private final Random random = new Random();
private final ConcurrentHashMap<String, ConcurrentHashMap<Long, AdvertisementResponse>> advertisementCache = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, AtomicInteger> keywordRanks = new ConcurrentHashMap<>();

@PostMapping
public List<AdvertisementResponse> getAdvertisements(
Expand All @@ -31,9 +35,18 @@ public List<AdvertisementResponse> getAdvertisements(
throw new RuntimeException(e);
}

String keyword = request.getKeyword();
ConcurrentHashMap<Long, AdvertisementResponse> keywordCache = advertisementCache.computeIfAbsent(keyword, k -> new ConcurrentHashMap<>());
AtomicInteger rank = keywordRanks.computeIfAbsent(keyword, k -> new AtomicInteger(0));

for (Long id : request.getIds()) {
int rank = 0;
responses.add(new AdvertisementResponse(id, ++rank, random.nextBoolean()));
AdvertisementResponse response = keywordCache.computeIfAbsent(id,
key -> {
boolean hasAd = random.nextBoolean();
int adRank = hasAd ? rank.incrementAndGet() : Integer.MAX_VALUE;
return new AdvertisementResponse(key, adRank, hasAd);
});
responses.add(response);
}

return responses;
Expand Down

0 comments on commit e139b51

Please sign in to comment.