From ddfd8b38105c74900a0eb9766392f4509cb7ee75 Mon Sep 17 00:00:00 2001 From: yangzl Date: Wed, 27 Nov 2024 10:29:18 +0800 Subject: [PATCH] refactor(ConsumerService): Optimize the implementation of getRateLimit method --- .../openapi/service/ConsumerService.java | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/apollo-portal/src/main/java/com/ctrip/framework/apollo/openapi/service/ConsumerService.java b/apollo-portal/src/main/java/com/ctrip/framework/apollo/openapi/service/ConsumerService.java index 9ab9e9d686d..e0676a18655 100644 --- a/apollo-portal/src/main/java/com/ctrip/framework/apollo/openapi/service/ConsumerService.java +++ b/apollo-portal/src/main/java/com/ctrip/framework/apollo/openapi/service/ConsumerService.java @@ -44,6 +44,7 @@ import com.google.common.hash.Hashing; import java.util.ArrayList; import java.util.Collections; +import java.util.Map; import java.util.Objects; import org.apache.commons.lang3.time.FastDateFormat; import org.springframework.data.domain.Pageable; @@ -235,7 +236,7 @@ private boolean isAllowCreateApplication(Long consumerId) { private Integer getRateLimit(Long consumerId) { List list = getRateLimit(Collections.singletonList(consumerId)); - if(CollectionUtils.isEmpty(list)){ + if (CollectionUtils.isEmpty(list)) { return 0; } return list.get(0); @@ -264,13 +265,16 @@ private List isAllowCreateApplication(List consumerIdList) { } private List getRateLimit(List consumerIds) { - List list = new ArrayList<>(consumerIds.size()); List consumerTokens = consumerTokenRepository.findByConsumerIdIn(consumerIds); - for (ConsumerToken consumerToken : consumerTokens) { - Integer rateLimit = consumerToken != null ? consumerToken.getRateLimit() : 0; - list.add(rateLimit); - } - return list; + Map consumerRateLimits = consumerTokens.stream() + .collect(Collectors.toMap( + ConsumerToken::getConsumerId, + consumerToken -> consumerToken.getRateLimit() != null ? consumerToken.getRateLimit() : 0 + )); + + return consumerIds.stream() + .map(id -> consumerRateLimits.getOrDefault(id, 0)) + .collect(Collectors.toList()); } private Role getCreateAppRole() {