diff --git a/service/advertisement-service/src/main/java/woowa/team4/bff/advertisementservice/AdvertisementController.java b/service/advertisement-service/src/main/java/woowa/team4/bff/advertisementservice/AdvertisementController.java index 700cf621..b03bbae6 100644 --- a/service/advertisement-service/src/main/java/woowa/team4/bff/advertisementservice/AdvertisementController.java +++ b/service/advertisement-service/src/main/java/woowa/team4/bff/advertisementservice/AdvertisementController.java @@ -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; @@ -18,6 +20,8 @@ public class AdvertisementController { private final Random random = new Random(); + private final ConcurrentHashMap> advertisementCache = new ConcurrentHashMap<>(); + private final ConcurrentHashMap keywordRanks = new ConcurrentHashMap<>(); @PostMapping public List getAdvertisements( @@ -31,9 +35,18 @@ public List getAdvertisements( throw new RuntimeException(e); } + String keyword = request.getKeyword(); + ConcurrentHashMap 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;