RateLimitCaller invoke with query param and headers.

pull/951/head
atomzhong 3 years ago
parent 07b946ed20
commit 05379093a1

@ -25,6 +25,7 @@ import javax.servlet.http.HttpServletRequest;
import com.tencent.cloud.polaris.ratelimit.spi.PolarisRateLimiterLabelServletResolver;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
@ -35,12 +36,22 @@ import org.springframework.stereotype.Component;
@Component
public class CustomLabelResolver implements PolarisRateLimiterLabelServletResolver {
@Value("${label.key-value:}")
private String[] keyValues;
@Override
public Map<String, String> resolve(HttpServletRequest request) {
// rate limit by some request params. such as query params, headers ..
return getLabels(keyValues);
}
static Map<String, String> getLabels(String[] keyValues) {
Map<String, String> labels = new HashMap<>();
labels.put("user", "zhangsan");
for (String kv : keyValues) {
String key = kv.substring(0, kv.indexOf(":"));
String value = kv.substring(kv.indexOf(":"));
labels.put(key, value);
}
return labels;
}

@ -17,14 +17,16 @@
package com.tencent.cloud.ratelimit.example.service.callee;
import java.util.HashMap;
import java.util.Map;
import com.tencent.cloud.polaris.ratelimit.spi.PolarisRateLimiterLabelReactiveResolver;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import static com.tencent.cloud.ratelimit.example.service.callee.CustomLabelResolver.getLabels;
/**
* resolver custom label from request.
*
@ -32,13 +34,13 @@ import org.springframework.web.server.ServerWebExchange;
*/
@Component
public class CustomLabelResolverReactive implements PolarisRateLimiterLabelReactiveResolver {
@Value("${label.key-value:}")
private String[] keyValues;
@Override
public Map<String, String> resolve(ServerWebExchange exchange) {
// rate limit by some request params. such as query params, headers ..
Map<String, String> labels = new HashMap<>();
labels.put("user", "zhangsan");
return labels;
return getLabels(keyValues);
}
}

@ -22,3 +22,6 @@ management:
logging:
level:
com.tencent.cloud.polaris: debug
label:
key-value: user:zhangsan, user2:lisi

@ -19,10 +19,12 @@ package com.tencent.cloud.ratelimit.example.service.caller;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -34,7 +36,9 @@ import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.HttpClientErrorException.TooManyRequests;
import org.springframework.web.client.RestClientException;
@ -55,7 +59,7 @@ public class Controller {
@Autowired
private WebClient.Builder webClientBuilder;
private String appName = "RateLimitCalleeService";
private final String appName = "RateLimitCalleeService";
/**
* Get information.
@ -72,25 +76,33 @@ public class Controller {
}
@GetMapping("/invoke/webclient")
public String invokeInfoWebClient() throws InterruptedException, ExecutionException {
public String invokeInfoWebClient(@RequestParam String value1, @RequestParam String value2, @RequestHeader Map<String, String> headers) throws InterruptedException, ExecutionException {
StringBuffer builder = new StringBuffer();
WebClient webClient = webClientBuilder.baseUrl("http://" + appName).build();
Consumer<HttpHeaders> headersConsumer = httpHeaders -> {
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpHeaders.add(entry.getKey(), entry.getValue());
}
};
List<Mono<String>> monoList = new ArrayList<>();
for (int i = 0; i < 30; i++) {
Mono<String> response = webClient.get()
.uri(uriBuilder -> uriBuilder
.path("/business/info/webclient")
.queryParam("yyy", "yyy")
.queryParam("value1", value1)
.queryParam("value2", value2)
.build()
)
.header("xxx", "xxx")
.headers(headersConsumer)
.retrieve()
.bodyToMono(String.class)
.doOnSuccess(s -> builder.append(s + "\n"))
.doOnSuccess(s -> builder.append(s).append("\n"))
.doOnError(e -> {
if (e instanceof WebClientResponseException) {
if (((WebClientResponseException) e).getRawStatusCode() == 429) {
builder.append("TooManyRequests ").append(index.incrementAndGet() + "\n");
builder.append("TooManyRequests ").append(index.incrementAndGet()).append("\n");
}
}
})
@ -111,26 +123,28 @@ public class Controller {
* @throws InterruptedException exception
*/
@GetMapping("/invoke")
public String invokeInfo() throws InterruptedException {
public String invokeInfo(@RequestParam String value1, @RequestParam String value2, @RequestHeader Map<String, String> headers) throws InterruptedException {
StringBuffer builder = new StringBuffer();
CountDownLatch count = new CountDownLatch(30);
for (int i = 0; i < 30; i++) {
new Thread(() -> {
try {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add("xxx", "xxx");
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpHeaders.add(entry.getKey(), entry.getValue());
}
ResponseEntity<String> entity = restTemplate.exchange(
"http://" + appName + "/business/info?yyy={yyy}",
"http://" + appName + "/business/info?value1={value1}&value2={value2}",
HttpMethod.GET,
new HttpEntity<>(httpHeaders),
String.class,
"yyy"
value1, value2
);
builder.append(entity.getBody() + "\n");
builder.append(entity.getBody()).append("\n");
}
catch (RestClientException e) {
if (e instanceof TooManyRequests) {
builder.append("TooManyRequests ").append(index.incrementAndGet() + "\n");
builder.append("TooManyRequests ").append(index.incrementAndGet()).append("\n");
}
else {
throw e;

@ -1,58 +0,0 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
*/
package com.tencent.cloud.ratelimit.example.service.caller;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import com.tencent.cloud.polaris.ratelimit.spi.PolarisRateLimiterLabelServletResolver;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* resolver custom label from request.
*
* @author atom
*/
@Component
public class CustomLabelResolver implements PolarisRateLimiterLabelServletResolver {
@Value("${label.key-value:}")
private String[] keyValues;
@Override
public Map<String, String> resolve(HttpServletRequest request) {
// rate limit by some request params. such as query params, headers ..
return getLabels(keyValues);
}
static Map<String, String> getLabels(String[] keyValues) {
Map<String, String> labels = new HashMap<>();
for (String kv : keyValues) {
String key = kv.substring(0, kv.indexOf(":"));
String value = kv.substring(kv.indexOf(":"));
labels.put(key, value);
}
return labels;
}
}

@ -1,46 +0,0 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.tencent.cloud.ratelimit.example.service.caller;
import java.util.Map;
import com.tencent.cloud.polaris.ratelimit.spi.PolarisRateLimiterLabelReactiveResolver;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import static com.tencent.cloud.ratelimit.example.service.caller.CustomLabelResolver.getLabels;
/**
* resolver custom label from request.
*
* @author atom
*/
@Component
public class CustomLabelResolverReactive implements PolarisRateLimiterLabelReactiveResolver {
@Value("${label.key-value:}")
private String[] keyValues;
@Override
public Map<String, String> resolve(ServerWebExchange exchange) {
// rate limit by some request params. such as query params, headers ..
return getLabels(keyValues);
}
}

@ -19,5 +19,3 @@ logging:
level:
com.tencent.cloud.polaris: debug
label:
key-value: user:zhangsan, user2:lisi

Loading…
Cancel
Save