commit
2b231f664c
@ -0,0 +1,90 @@
|
|||||||
|
/*
|
||||||
|
* 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.metadata.core;
|
||||||
|
|
||||||
|
import java.io.UnsupportedEncodingException;
|
||||||
|
import java.net.URLEncoder;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import com.tencent.cloud.common.metadata.MetadataContext;
|
||||||
|
import com.tencent.cloud.common.metadata.MetadataContextHolder;
|
||||||
|
import com.tencent.cloud.common.util.JacksonUtils;
|
||||||
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
|
import org.springframework.util.CollectionUtils;
|
||||||
|
import org.springframework.web.reactive.function.client.ClientRequest;
|
||||||
|
import org.springframework.web.reactive.function.client.ClientResponse;
|
||||||
|
import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
|
||||||
|
import org.springframework.web.reactive.function.client.ExchangeFunction;
|
||||||
|
|
||||||
|
import static com.tencent.cloud.common.constant.ContextConstant.UTF_8;
|
||||||
|
import static com.tencent.cloud.common.constant.MetadataConstant.HeaderName.CUSTOM_DISPOSABLE_METADATA;
|
||||||
|
import static com.tencent.cloud.common.constant.MetadataConstant.HeaderName.CUSTOM_METADATA;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* web client filter used for writing metadata in HTTP request header.
|
||||||
|
*
|
||||||
|
* @author sean yu
|
||||||
|
*/
|
||||||
|
public class EncodeTransferMedataWebClientFilter implements ExchangeFilterFunction {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Mono<ClientResponse> filter(ClientRequest clientRequest, ExchangeFunction next) {
|
||||||
|
MetadataContext metadataContext = MetadataContextHolder.get();
|
||||||
|
Map<String, String> customMetadata = metadataContext.getCustomMetadata();
|
||||||
|
Map<String, String> disposableMetadata = metadataContext.getDisposableMetadata();
|
||||||
|
Map<String, String> transHeaders = metadataContext.getTransHeadersKV();
|
||||||
|
|
||||||
|
ClientRequest.Builder requestBuilder = ClientRequest.from(clientRequest);
|
||||||
|
|
||||||
|
this.buildMetadataHeader(requestBuilder, customMetadata, CUSTOM_METADATA);
|
||||||
|
this.buildMetadataHeader(requestBuilder, disposableMetadata, CUSTOM_DISPOSABLE_METADATA);
|
||||||
|
this.buildTransmittedHeader(requestBuilder, transHeaders);
|
||||||
|
|
||||||
|
ClientRequest request = requestBuilder.build();
|
||||||
|
|
||||||
|
return next.exchange(request);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void buildTransmittedHeader(ClientRequest.Builder requestBuilder, Map<String, String> transHeaders) {
|
||||||
|
if (!CollectionUtils.isEmpty(transHeaders)) {
|
||||||
|
transHeaders.forEach(requestBuilder::header);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set metadata into the request header for {@link ClientRequest} .
|
||||||
|
* @param requestBuilder instance of {@link ClientRequest.Builder}
|
||||||
|
* @param metadata metadata map .
|
||||||
|
* @param headerName target metadata http header name .
|
||||||
|
*/
|
||||||
|
private void buildMetadataHeader(ClientRequest.Builder requestBuilder, Map<String, String> metadata, String headerName) {
|
||||||
|
if (!CollectionUtils.isEmpty(metadata)) {
|
||||||
|
String encodedMetadata = JacksonUtils.serialize2Json(metadata);
|
||||||
|
try {
|
||||||
|
requestBuilder.header(headerName, URLEncoder.encode(encodedMetadata, UTF_8));
|
||||||
|
}
|
||||||
|
catch (UnsupportedEncodingException e) {
|
||||||
|
requestBuilder.header(headerName, encodedMetadata);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,84 @@
|
|||||||
|
/*
|
||||||
|
* 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.metadata.core;
|
||||||
|
|
||||||
|
import com.tencent.cloud.common.metadata.MetadataContext;
|
||||||
|
import com.tencent.cloud.common.metadata.MetadataContextHolder;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.boot.test.web.server.LocalServerPort;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.test.context.junit.jupiter.SpringExtension;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
import org.springframework.web.reactive.function.client.WebClient;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test for {@link EncodeTransferMedataWebClientFilter}.
|
||||||
|
*
|
||||||
|
* @author sean yu
|
||||||
|
*/
|
||||||
|
@ExtendWith(SpringExtension.class)
|
||||||
|
@SpringBootTest(webEnvironment = RANDOM_PORT,
|
||||||
|
classes = EncodeTransferMedataWebClientFilterTest.TestApplication.class,
|
||||||
|
properties = {"spring.config.location = classpath:application-test.yml"})
|
||||||
|
public class EncodeTransferMedataWebClientFilterTest {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private WebClient.Builder webClientBuilder;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testTransitiveMetadataFromApplicationConfig() {
|
||||||
|
MetadataContext metadataContext = MetadataContextHolder.get();
|
||||||
|
metadataContext.setTransHeadersKV("xxx", "xxx");
|
||||||
|
String metadata = webClientBuilder.baseUrl("http://localhost:" + localServerPort).build()
|
||||||
|
.get()
|
||||||
|
.uri("/test")
|
||||||
|
.retrieve()
|
||||||
|
.bodyToMono(String.class)
|
||||||
|
.block();
|
||||||
|
assertThat(metadata).isEqualTo("2");
|
||||||
|
}
|
||||||
|
|
||||||
|
@LocalServerPort
|
||||||
|
private int localServerPort;
|
||||||
|
|
||||||
|
|
||||||
|
@SpringBootApplication
|
||||||
|
@RestController
|
||||||
|
protected static class TestApplication {
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public WebClient.Builder webClientBuilder() {
|
||||||
|
return WebClient.builder();
|
||||||
|
}
|
||||||
|
|
||||||
|
@RequestMapping("/test")
|
||||||
|
public String test() {
|
||||||
|
return MetadataContextHolder.get().getContext(MetadataContext.FRAGMENT_TRANSITIVE, "b");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,97 @@
|
|||||||
|
/*
|
||||||
|
* 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.polaris.circuitbreaker.feign;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.lang.reflect.Method;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import com.tencent.polaris.api.pojo.CircuitBreakerStatus;
|
||||||
|
import com.tencent.polaris.circuitbreak.client.exception.CallAbortedException;
|
||||||
|
import feign.Request;
|
||||||
|
import feign.RequestTemplate;
|
||||||
|
import feign.Response;
|
||||||
|
import feign.codec.Decoder;
|
||||||
|
|
||||||
|
import org.springframework.cloud.openfeign.FallbackFactory;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PolarisCircuitBreakerFallbackFactory.
|
||||||
|
*
|
||||||
|
* @author sean yu
|
||||||
|
*/
|
||||||
|
public class PolarisCircuitBreakerFallbackFactory implements FallbackFactory {
|
||||||
|
|
||||||
|
private final Decoder decoder;
|
||||||
|
|
||||||
|
public PolarisCircuitBreakerFallbackFactory(Decoder decoder) {
|
||||||
|
this.decoder = decoder;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Object create(Throwable t) {
|
||||||
|
return new DefaultFallback(t, decoder);
|
||||||
|
}
|
||||||
|
|
||||||
|
public class DefaultFallback {
|
||||||
|
|
||||||
|
private final Throwable t;
|
||||||
|
|
||||||
|
private final Decoder decoder;
|
||||||
|
|
||||||
|
public DefaultFallback(Throwable t, Decoder decoder) {
|
||||||
|
this.t = t;
|
||||||
|
this.decoder = decoder;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Object fallback(Method method) {
|
||||||
|
if (t instanceof CallAbortedException) {
|
||||||
|
CircuitBreakerStatus.FallbackInfo fallbackInfo = ((CallAbortedException) t).getFallbackInfo();
|
||||||
|
if (fallbackInfo != null) {
|
||||||
|
Response.Builder responseBuilder = Response.builder()
|
||||||
|
.status(fallbackInfo.getCode());
|
||||||
|
if (fallbackInfo.getHeaders() != null) {
|
||||||
|
Map<String, Collection<String>> headers = new HashMap<>();
|
||||||
|
fallbackInfo.getHeaders().forEach((k, v) -> headers.put(k, Collections.singleton(v)));
|
||||||
|
responseBuilder.headers(headers);
|
||||||
|
}
|
||||||
|
if (fallbackInfo.getBody() != null) {
|
||||||
|
responseBuilder.body(fallbackInfo.getBody(), StandardCharsets.UTF_8);
|
||||||
|
}
|
||||||
|
// Feign Response need a nonnull Request,
|
||||||
|
// which is not important in fallback response (no real request),
|
||||||
|
// so we create a fake one
|
||||||
|
Request fakeRequest = Request.create(Request.HttpMethod.GET, "/", new HashMap<>(), Request.Body.empty(), new RequestTemplate());
|
||||||
|
responseBuilder.request(fakeRequest);
|
||||||
|
|
||||||
|
try (Response response = responseBuilder.build()) {
|
||||||
|
return decoder.decode(response, method.getGenericReturnType());
|
||||||
|
}
|
||||||
|
catch (IOException e) {
|
||||||
|
throw new IllegalStateException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw new IllegalStateException(t);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,94 @@
|
|||||||
|
/*
|
||||||
|
* 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.polaris.circuitbreaker.feign;
|
||||||
|
|
||||||
|
import feign.Feign;
|
||||||
|
import feign.Target;
|
||||||
|
|
||||||
|
import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory;
|
||||||
|
import org.springframework.cloud.openfeign.CircuitBreakerNameResolver;
|
||||||
|
import org.springframework.cloud.openfeign.FallbackFactory;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PolarisFeignCircuitBreaker, mostly copy from {@link org.springframework.cloud.openfeign.FeignCircuitBreaker}, but giving Polaris modification.
|
||||||
|
*
|
||||||
|
* @author sean yu
|
||||||
|
*/
|
||||||
|
public final class PolarisFeignCircuitBreaker {
|
||||||
|
|
||||||
|
private PolarisFeignCircuitBreaker() {
|
||||||
|
throw new IllegalStateException("Don't instantiate a utility class");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return builder for Feign CircuitBreaker integration
|
||||||
|
*/
|
||||||
|
public static PolarisFeignCircuitBreaker.Builder builder() {
|
||||||
|
return new PolarisFeignCircuitBreaker.Builder();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Builder for Feign CircuitBreaker integration.
|
||||||
|
*/
|
||||||
|
public static final class Builder extends Feign.Builder {
|
||||||
|
|
||||||
|
public Builder() {
|
||||||
|
}
|
||||||
|
|
||||||
|
private CircuitBreakerFactory circuitBreakerFactory;
|
||||||
|
|
||||||
|
private String feignClientName;
|
||||||
|
|
||||||
|
private CircuitBreakerNameResolver circuitBreakerNameResolver;
|
||||||
|
|
||||||
|
public PolarisFeignCircuitBreaker.Builder circuitBreakerFactory(CircuitBreakerFactory circuitBreakerFactory) {
|
||||||
|
this.circuitBreakerFactory = circuitBreakerFactory;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public PolarisFeignCircuitBreaker.Builder feignClientName(String feignClientName) {
|
||||||
|
this.feignClientName = feignClientName;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public PolarisFeignCircuitBreaker.Builder circuitBreakerNameResolver(CircuitBreakerNameResolver circuitBreakerNameResolver) {
|
||||||
|
this.circuitBreakerNameResolver = circuitBreakerNameResolver;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public <T> T target(Target<T> target, T fallback) {
|
||||||
|
return build(fallback != null ? new FallbackFactory.Default<T>(fallback) : null).newInstance(target);
|
||||||
|
}
|
||||||
|
|
||||||
|
public <T> T target(Target<T> target, FallbackFactory<? extends T> fallbackFactory) {
|
||||||
|
return build(fallbackFactory).newInstance(target);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public <T> T target(Target<T> target) {
|
||||||
|
return build(null).newInstance(target);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Feign build(final FallbackFactory<?> nullableFallbackFactory) {
|
||||||
|
this.invocationHandlerFactory((target, dispatch) -> new PolarisFeignCircuitBreakerInvocationHandler(
|
||||||
|
circuitBreakerFactory, feignClientName, target, dispatch, nullableFallbackFactory, circuitBreakerNameResolver, this.decoder));
|
||||||
|
return this.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,200 @@
|
|||||||
|
/*
|
||||||
|
* 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.polaris.circuitbreaker.feign;
|
||||||
|
|
||||||
|
import java.lang.reflect.InvocationHandler;
|
||||||
|
import java.lang.reflect.InvocationTargetException;
|
||||||
|
import java.lang.reflect.Method;
|
||||||
|
import java.lang.reflect.Proxy;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.function.Function;
|
||||||
|
import java.util.function.Supplier;
|
||||||
|
|
||||||
|
import feign.InvocationHandlerFactory;
|
||||||
|
import feign.Target;
|
||||||
|
import feign.codec.Decoder;
|
||||||
|
|
||||||
|
import org.springframework.cloud.client.circuitbreaker.CircuitBreaker;
|
||||||
|
import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory;
|
||||||
|
import org.springframework.cloud.client.circuitbreaker.NoFallbackAvailableException;
|
||||||
|
import org.springframework.cloud.openfeign.CircuitBreakerNameResolver;
|
||||||
|
import org.springframework.cloud.openfeign.FallbackFactory;
|
||||||
|
import org.springframework.web.context.request.RequestAttributes;
|
||||||
|
import org.springframework.web.context.request.RequestContextHolder;
|
||||||
|
|
||||||
|
import static feign.Util.checkNotNull;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PolarisFeignCircuitBreakerInvocationHandler, mostly copy from {@link org.springframework.cloud.openfeign.FeignCircuitBreakerInvocationHandler}, but giving Polaris modification.
|
||||||
|
*
|
||||||
|
* @author sean yu
|
||||||
|
*/
|
||||||
|
public class PolarisFeignCircuitBreakerInvocationHandler implements InvocationHandler {
|
||||||
|
|
||||||
|
private final CircuitBreakerFactory factory;
|
||||||
|
|
||||||
|
private final String feignClientName;
|
||||||
|
|
||||||
|
private final Target<?> target;
|
||||||
|
|
||||||
|
private final Map<Method, InvocationHandlerFactory.MethodHandler> dispatch;
|
||||||
|
|
||||||
|
private final FallbackFactory<?> nullableFallbackFactory;
|
||||||
|
|
||||||
|
private final Map<Method, Method> fallbackMethodMap;
|
||||||
|
|
||||||
|
private final CircuitBreakerNameResolver circuitBreakerNameResolver;
|
||||||
|
|
||||||
|
private final Decoder decoder;
|
||||||
|
|
||||||
|
public PolarisFeignCircuitBreakerInvocationHandler(CircuitBreakerFactory factory, String feignClientName, Target<?> target,
|
||||||
|
Map<Method, InvocationHandlerFactory.MethodHandler> dispatch, FallbackFactory<?> nullableFallbackFactory,
|
||||||
|
CircuitBreakerNameResolver circuitBreakerNameResolver, Decoder decoder) {
|
||||||
|
this.factory = factory;
|
||||||
|
this.feignClientName = feignClientName;
|
||||||
|
this.target = checkNotNull(target, "target");
|
||||||
|
this.dispatch = checkNotNull(dispatch, "dispatch");
|
||||||
|
this.fallbackMethodMap = toFallbackMethod(dispatch);
|
||||||
|
this.nullableFallbackFactory = nullableFallbackFactory;
|
||||||
|
this.circuitBreakerNameResolver = circuitBreakerNameResolver;
|
||||||
|
this.decoder = decoder;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
|
||||||
|
// early exit if the invoked method is from java.lang.Object
|
||||||
|
// code is the same as ReflectiveFeign.FeignInvocationHandler
|
||||||
|
if ("equals".equals(method.getName())) {
|
||||||
|
try {
|
||||||
|
Object otherHandler = args.length > 0 && args[0] != null ? Proxy.getInvocationHandler(args[0]) : null;
|
||||||
|
return equals(otherHandler);
|
||||||
|
}
|
||||||
|
catch (IllegalArgumentException e) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if ("hashCode".equals(method.getName())) {
|
||||||
|
return hashCode();
|
||||||
|
}
|
||||||
|
else if ("toString".equals(method.getName())) {
|
||||||
|
return toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
String circuitName = circuitBreakerNameResolver.resolveCircuitBreakerName(feignClientName, target, method);
|
||||||
|
CircuitBreaker circuitBreaker = factory.create(circuitName);
|
||||||
|
Supplier<Object> supplier = asSupplier(method, args);
|
||||||
|
Function<Throwable, Object> fallbackFunction;
|
||||||
|
if (this.nullableFallbackFactory != null) {
|
||||||
|
fallbackFunction = throwable -> {
|
||||||
|
Object fallback = this.nullableFallbackFactory.create(throwable);
|
||||||
|
try {
|
||||||
|
return this.fallbackMethodMap.get(method).invoke(fallback, args);
|
||||||
|
}
|
||||||
|
catch (Exception exception) {
|
||||||
|
unwrapAndRethrow(exception);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
fallbackFunction = throwable -> {
|
||||||
|
PolarisCircuitBreakerFallbackFactory.DefaultFallback fallback =
|
||||||
|
(PolarisCircuitBreakerFallbackFactory.DefaultFallback) new PolarisCircuitBreakerFallbackFactory(this.decoder).create(throwable);
|
||||||
|
return fallback.fallback(method);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return circuitBreaker.run(supplier, fallbackFunction);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void unwrapAndRethrow(Exception exception) {
|
||||||
|
if (exception instanceof InvocationTargetException || exception instanceof NoFallbackAvailableException) {
|
||||||
|
Throwable underlyingException = exception.getCause();
|
||||||
|
if (underlyingException instanceof RuntimeException) {
|
||||||
|
throw (RuntimeException) underlyingException;
|
||||||
|
}
|
||||||
|
if (underlyingException != null) {
|
||||||
|
throw new IllegalStateException(underlyingException);
|
||||||
|
}
|
||||||
|
throw new IllegalStateException(exception);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Supplier<Object> asSupplier(final Method method, final Object[] args) {
|
||||||
|
final RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
|
||||||
|
final Thread caller = Thread.currentThread();
|
||||||
|
return () -> {
|
||||||
|
boolean isAsync = caller != Thread.currentThread();
|
||||||
|
try {
|
||||||
|
if (isAsync) {
|
||||||
|
RequestContextHolder.setRequestAttributes(requestAttributes);
|
||||||
|
}
|
||||||
|
return dispatch.get(method).invoke(args);
|
||||||
|
}
|
||||||
|
catch (RuntimeException throwable) {
|
||||||
|
throw throwable;
|
||||||
|
}
|
||||||
|
catch (Throwable throwable) {
|
||||||
|
throw new RuntimeException(throwable);
|
||||||
|
}
|
||||||
|
finally {
|
||||||
|
if (isAsync) {
|
||||||
|
RequestContextHolder.resetRequestAttributes();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* If the method param of {@link InvocationHandler#invoke(Object, Method, Object[])}
|
||||||
|
* is not accessible, i.e in a package-private interface, the fallback call will cause
|
||||||
|
* of access restrictions. But methods in dispatch are copied methods. So setting
|
||||||
|
* access to dispatch method doesn't take effect to the method in
|
||||||
|
* InvocationHandler.invoke. Use map to store a copy of method to invoke the fallback
|
||||||
|
* to bypass this and reducing the count of reflection calls.
|
||||||
|
* @return cached methods map for fallback invoking
|
||||||
|
*/
|
||||||
|
static Map<Method, Method> toFallbackMethod(Map<Method, InvocationHandlerFactory.MethodHandler> dispatch) {
|
||||||
|
Map<Method, Method> result = new LinkedHashMap<>();
|
||||||
|
for (Method method : dispatch.keySet()) {
|
||||||
|
method.setAccessible(true);
|
||||||
|
result.put(method, method);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object obj) {
|
||||||
|
if (obj instanceof PolarisFeignCircuitBreakerInvocationHandler) {
|
||||||
|
PolarisFeignCircuitBreakerInvocationHandler other = (PolarisFeignCircuitBreakerInvocationHandler) obj;
|
||||||
|
return this.target.equals(other.target);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
return this.target.hashCode();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return this.target.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,103 @@
|
|||||||
|
/*
|
||||||
|
* 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.polaris.circuitbreaker.feign;
|
||||||
|
|
||||||
|
import feign.Feign;
|
||||||
|
import feign.Target;
|
||||||
|
|
||||||
|
import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory;
|
||||||
|
import org.springframework.cloud.openfeign.CircuitBreakerNameResolver;
|
||||||
|
import org.springframework.cloud.openfeign.FallbackFactory;
|
||||||
|
import org.springframework.cloud.openfeign.FeignClientFactory;
|
||||||
|
import org.springframework.cloud.openfeign.FeignClientFactoryBean;
|
||||||
|
import org.springframework.cloud.openfeign.Targeter;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PolarisFeignCircuitBreakerTargeter, mostly copy from {@link org.springframework.cloud.openfeign.FeignCircuitBreakerTargeter}, but giving Polaris modification.
|
||||||
|
*
|
||||||
|
* @author sean yu
|
||||||
|
*/
|
||||||
|
public class PolarisFeignCircuitBreakerTargeter implements Targeter {
|
||||||
|
|
||||||
|
private final CircuitBreakerFactory circuitBreakerFactory;
|
||||||
|
|
||||||
|
private final CircuitBreakerNameResolver circuitBreakerNameResolver;
|
||||||
|
|
||||||
|
public PolarisFeignCircuitBreakerTargeter(CircuitBreakerFactory circuitBreakerFactory, CircuitBreakerNameResolver circuitBreakerNameResolver) {
|
||||||
|
this.circuitBreakerFactory = circuitBreakerFactory;
|
||||||
|
this.circuitBreakerNameResolver = circuitBreakerNameResolver;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public <T> T target(FeignClientFactoryBean factory, Feign.Builder feign, FeignClientFactory context,
|
||||||
|
Target.HardCodedTarget<T> target) {
|
||||||
|
if (!(feign instanceof PolarisFeignCircuitBreaker.Builder)) {
|
||||||
|
return feign.target(target);
|
||||||
|
}
|
||||||
|
PolarisFeignCircuitBreaker.Builder builder = (PolarisFeignCircuitBreaker.Builder) feign;
|
||||||
|
String name = !StringUtils.hasText(factory.getContextId()) ? factory.getName() : factory.getContextId();
|
||||||
|
Class<?> fallback = factory.getFallback();
|
||||||
|
if (fallback != void.class) {
|
||||||
|
return targetWithFallback(name, context, target, builder, fallback);
|
||||||
|
}
|
||||||
|
Class<?> fallbackFactory = factory.getFallbackFactory();
|
||||||
|
if (fallbackFactory != void.class) {
|
||||||
|
return targetWithFallbackFactory(name, context, target, builder, fallbackFactory);
|
||||||
|
}
|
||||||
|
return builder(name, builder).target(target);
|
||||||
|
}
|
||||||
|
|
||||||
|
private <T> T targetWithFallbackFactory(String feignClientName, FeignClientFactory context,
|
||||||
|
Target.HardCodedTarget<T> target, PolarisFeignCircuitBreaker.Builder builder, Class<?> fallbackFactoryClass) {
|
||||||
|
FallbackFactory<? extends T> fallbackFactory = (FallbackFactory<? extends T>) getFromContext("fallbackFactory",
|
||||||
|
feignClientName, context, fallbackFactoryClass, FallbackFactory.class);
|
||||||
|
return builder(feignClientName, builder).target(target, fallbackFactory);
|
||||||
|
}
|
||||||
|
|
||||||
|
private <T> T targetWithFallback(String feignClientName, FeignClientFactory context, Target.HardCodedTarget<T> target,
|
||||||
|
PolarisFeignCircuitBreaker.Builder builder, Class<?> fallback) {
|
||||||
|
T fallbackInstance = getFromContext("fallback", feignClientName, context, fallback, target.type());
|
||||||
|
return builder(feignClientName, builder).target(target, fallbackInstance);
|
||||||
|
}
|
||||||
|
|
||||||
|
private <T> T getFromContext(String fallbackMechanism, String feignClientName, FeignClientFactory context,
|
||||||
|
Class<?> beanType, Class<T> targetType) {
|
||||||
|
Object fallbackInstance = context.getInstance(feignClientName, beanType);
|
||||||
|
if (fallbackInstance == null) {
|
||||||
|
throw new IllegalStateException(
|
||||||
|
String.format("No " + fallbackMechanism + " instance of type %s found for feign client %s",
|
||||||
|
beanType, feignClientName));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!targetType.isAssignableFrom(beanType)) {
|
||||||
|
throw new IllegalStateException(String.format("Incompatible " + fallbackMechanism
|
||||||
|
+ " instance. Fallback/fallbackFactory of type %s is not assignable to %s for feign client %s",
|
||||||
|
beanType, targetType, feignClientName));
|
||||||
|
}
|
||||||
|
return (T) fallbackInstance;
|
||||||
|
}
|
||||||
|
|
||||||
|
private PolarisFeignCircuitBreaker.Builder builder(String feignClientName, PolarisFeignCircuitBreaker.Builder builder) {
|
||||||
|
return builder
|
||||||
|
.circuitBreakerFactory(circuitBreakerFactory)
|
||||||
|
.feignClientName(feignClientName)
|
||||||
|
.circuitBreakerNameResolver(circuitBreakerNameResolver);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,54 @@
|
|||||||
|
/*
|
||||||
|
* 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.polaris.circuitbreaker.resttemplate;
|
||||||
|
|
||||||
|
import java.lang.annotation.Documented;
|
||||||
|
import java.lang.annotation.ElementType;
|
||||||
|
import java.lang.annotation.Retention;
|
||||||
|
import java.lang.annotation.RetentionPolicy;
|
||||||
|
import java.lang.annotation.Target;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PolarisCircuitBreaker annotation.
|
||||||
|
* if coded fallback or fallbackClass provided, RestTemplate will always return fallback when any exception occurs,
|
||||||
|
* if none coded fallback or fallbackClass provided, RestTemplate will return fallback response from Polaris server when fallback occurs.
|
||||||
|
* fallback and fallbackClass cannot provide at same time.
|
||||||
|
*
|
||||||
|
* @author sean yu
|
||||||
|
*/
|
||||||
|
@Target({ ElementType.METHOD })
|
||||||
|
@Retention(RetentionPolicy.RUNTIME)
|
||||||
|
@Documented
|
||||||
|
public @interface PolarisCircuitBreaker {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* a fallback string, will return a response { status: 200, body: fallback string} when any exception occurs.
|
||||||
|
*
|
||||||
|
* @return fallback string
|
||||||
|
*/
|
||||||
|
String fallback() default "";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* a fallback Class, will return a PolarisCircuitBreakerHttpResponse when any exception occurs.
|
||||||
|
* fallback Class must be a spring bean.
|
||||||
|
*
|
||||||
|
* @return PolarisCircuitBreakerFallback
|
||||||
|
*/
|
||||||
|
Class<? extends PolarisCircuitBreakerFallback> fallbackClass() default PolarisCircuitBreakerFallback.class;
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,29 @@
|
|||||||
|
/*
|
||||||
|
* 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.polaris.circuitbreaker.resttemplate;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PolarisCircuitBreakerFallback.
|
||||||
|
*
|
||||||
|
* @author sean yu
|
||||||
|
*/
|
||||||
|
public interface PolarisCircuitBreakerFallback {
|
||||||
|
|
||||||
|
PolarisCircuitBreakerHttpResponse fallback();
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,105 @@
|
|||||||
|
/*
|
||||||
|
* 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.polaris.circuitbreaker.resttemplate;
|
||||||
|
|
||||||
|
import java.io.ByteArrayInputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import com.tencent.polaris.api.pojo.CircuitBreakerStatus;
|
||||||
|
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.client.AbstractClientHttpResponse;
|
||||||
|
|
||||||
|
import static com.tencent.cloud.rpc.enhancement.resttemplate.EnhancedRestTemplateReporter.POLARIS_CIRCUIT_BREAKER_FALLBACK_HEADER;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PolarisCircuitBreakerHttpResponse.
|
||||||
|
*
|
||||||
|
* @author sean yu
|
||||||
|
*/
|
||||||
|
public class PolarisCircuitBreakerHttpResponse extends AbstractClientHttpResponse {
|
||||||
|
|
||||||
|
private final CircuitBreakerStatus.FallbackInfo fallbackInfo;
|
||||||
|
|
||||||
|
private HttpHeaders headers = new HttpHeaders();
|
||||||
|
|
||||||
|
private InputStream body;
|
||||||
|
|
||||||
|
public PolarisCircuitBreakerHttpResponse(int code) {
|
||||||
|
this(new CircuitBreakerStatus.FallbackInfo(code, null, null));
|
||||||
|
}
|
||||||
|
|
||||||
|
public PolarisCircuitBreakerHttpResponse(int code, String body) {
|
||||||
|
this(new CircuitBreakerStatus.FallbackInfo(code, null, body));
|
||||||
|
}
|
||||||
|
|
||||||
|
public PolarisCircuitBreakerHttpResponse(int code, Map<String, String> headers, String body) {
|
||||||
|
this(new CircuitBreakerStatus.FallbackInfo(code, headers, body));
|
||||||
|
}
|
||||||
|
|
||||||
|
PolarisCircuitBreakerHttpResponse(CircuitBreakerStatus.FallbackInfo fallbackInfo) {
|
||||||
|
this.fallbackInfo = fallbackInfo;
|
||||||
|
headers.add(POLARIS_CIRCUIT_BREAKER_FALLBACK_HEADER, "true");
|
||||||
|
if (fallbackInfo.getHeaders() != null) {
|
||||||
|
fallbackInfo.getHeaders().forEach(headers::add);
|
||||||
|
}
|
||||||
|
if (fallbackInfo.getBody() != null) {
|
||||||
|
body = new ByteArrayInputStream(fallbackInfo.getBody().getBytes());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final int getRawStatusCode() {
|
||||||
|
return fallbackInfo.getCode();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final String getStatusText() {
|
||||||
|
HttpStatus status = HttpStatus.resolve(getRawStatusCode());
|
||||||
|
return (status != null ? status.getReasonPhrase() : "");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final void close() {
|
||||||
|
if (this.body != null) {
|
||||||
|
try {
|
||||||
|
this.body.close();
|
||||||
|
}
|
||||||
|
catch (IOException e) {
|
||||||
|
// Ignore exception on close...
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final InputStream getBody() {
|
||||||
|
return this.body;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final HttpHeaders getHeaders() {
|
||||||
|
return this.headers;
|
||||||
|
}
|
||||||
|
|
||||||
|
public CircuitBreakerStatus.FallbackInfo getFallbackInfo() {
|
||||||
|
return this.fallbackInfo;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,125 @@
|
|||||||
|
/*
|
||||||
|
* 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.polaris.circuitbreaker.resttemplate;
|
||||||
|
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
|
||||||
|
import org.springframework.beans.BeansException;
|
||||||
|
import org.springframework.beans.factory.config.BeanDefinition;
|
||||||
|
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
|
||||||
|
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
|
||||||
|
import org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor;
|
||||||
|
import org.springframework.beans.factory.support.RootBeanDefinition;
|
||||||
|
import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory;
|
||||||
|
import org.springframework.context.ApplicationContext;
|
||||||
|
import org.springframework.core.type.MethodMetadata;
|
||||||
|
import org.springframework.core.type.StandardMethodMetadata;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
import org.springframework.web.client.RestTemplate;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PolarisCircuitBreakerRestTemplateBeanPostProcessor.
|
||||||
|
*
|
||||||
|
* @author sean yu
|
||||||
|
*/
|
||||||
|
public class PolarisCircuitBreakerRestTemplateBeanPostProcessor implements MergedBeanDefinitionPostProcessor {
|
||||||
|
|
||||||
|
private final ApplicationContext applicationContext;
|
||||||
|
|
||||||
|
public PolarisCircuitBreakerRestTemplateBeanPostProcessor(ApplicationContext applicationContext) {
|
||||||
|
this.applicationContext = applicationContext;
|
||||||
|
}
|
||||||
|
|
||||||
|
private final ConcurrentHashMap<String, PolarisCircuitBreaker> cache = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
|
private void checkPolarisCircuitBreakerRestTemplate(PolarisCircuitBreaker polarisCircuitBreaker) {
|
||||||
|
if (
|
||||||
|
StringUtils.hasText(polarisCircuitBreaker.fallback()) &&
|
||||||
|
!PolarisCircuitBreakerFallback.class.toGenericString().equals(polarisCircuitBreaker.fallbackClass().toGenericString())
|
||||||
|
) {
|
||||||
|
throw new IllegalArgumentException("PolarisCircuitBreaker's fallback and fallbackClass could not set at sametime !");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
|
||||||
|
if (checkAnnotated(beanDefinition, beanType, beanName)) {
|
||||||
|
PolarisCircuitBreaker polarisCircuitBreaker;
|
||||||
|
if (beanDefinition.getSource() instanceof StandardMethodMetadata) {
|
||||||
|
polarisCircuitBreaker = ((StandardMethodMetadata) beanDefinition.getSource()).getIntrospectedMethod()
|
||||||
|
.getAnnotation(PolarisCircuitBreaker.class);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
polarisCircuitBreaker = beanDefinition.getResolvedFactoryMethod()
|
||||||
|
.getAnnotation(PolarisCircuitBreaker.class);
|
||||||
|
}
|
||||||
|
checkPolarisCircuitBreakerRestTemplate(polarisCircuitBreaker);
|
||||||
|
cache.put(beanName, polarisCircuitBreaker);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
|
||||||
|
if (cache.containsKey(beanName)) {
|
||||||
|
// add interceptor for each RestTemplate with @PolarisCircuitBreaker annotation
|
||||||
|
StringBuilder interceptorBeanNamePrefix = new StringBuilder();
|
||||||
|
PolarisCircuitBreaker polarisCircuitBreaker = cache.get(beanName);
|
||||||
|
interceptorBeanNamePrefix
|
||||||
|
.append(StringUtils.uncapitalize(
|
||||||
|
PolarisCircuitBreaker.class.getSimpleName()))
|
||||||
|
.append("_")
|
||||||
|
.append(polarisCircuitBreaker.fallback())
|
||||||
|
.append("_")
|
||||||
|
.append(polarisCircuitBreaker.fallbackClass().getSimpleName());
|
||||||
|
RestTemplate restTemplate = (RestTemplate) bean;
|
||||||
|
String interceptorBeanName = interceptorBeanNamePrefix + "@" + bean;
|
||||||
|
CircuitBreakerFactory circuitBreakerFactory = this.applicationContext.getBean(CircuitBreakerFactory.class);
|
||||||
|
registerBean(interceptorBeanName, polarisCircuitBreaker, applicationContext, circuitBreakerFactory, restTemplate);
|
||||||
|
PolarisCircuitBreakerRestTemplateInterceptor polarisCircuitBreakerRestTemplateInterceptor = applicationContext
|
||||||
|
.getBean(interceptorBeanName, PolarisCircuitBreakerRestTemplateInterceptor.class);
|
||||||
|
restTemplate.getInterceptors().add(0, polarisCircuitBreakerRestTemplateInterceptor);
|
||||||
|
}
|
||||||
|
return bean;
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean checkAnnotated(RootBeanDefinition beanDefinition,
|
||||||
|
Class<?> beanType, String beanName) {
|
||||||
|
return beanName != null && beanType == RestTemplate.class
|
||||||
|
&& beanDefinition.getSource() instanceof MethodMetadata
|
||||||
|
&& ((MethodMetadata) beanDefinition.getSource())
|
||||||
|
.isAnnotated(PolarisCircuitBreaker.class.getName());
|
||||||
|
}
|
||||||
|
|
||||||
|
private void registerBean(String interceptorBeanName, PolarisCircuitBreaker polarisCircuitBreaker,
|
||||||
|
ApplicationContext applicationContext, CircuitBreakerFactory circuitBreakerFactory, RestTemplate restTemplate) {
|
||||||
|
// register PolarisCircuitBreakerRestTemplateInterceptor bean
|
||||||
|
DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) applicationContext
|
||||||
|
.getAutowireCapableBeanFactory();
|
||||||
|
BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder
|
||||||
|
.genericBeanDefinition(PolarisCircuitBreakerRestTemplateInterceptor.class);
|
||||||
|
beanDefinitionBuilder.addConstructorArgValue(polarisCircuitBreaker);
|
||||||
|
beanDefinitionBuilder.addConstructorArgValue(applicationContext);
|
||||||
|
beanDefinitionBuilder.addConstructorArgValue(circuitBreakerFactory);
|
||||||
|
beanDefinitionBuilder.addConstructorArgValue(restTemplate);
|
||||||
|
BeanDefinition interceptorBeanDefinition = beanDefinitionBuilder
|
||||||
|
.getRawBeanDefinition();
|
||||||
|
beanFactory.registerBeanDefinition(interceptorBeanName,
|
||||||
|
interceptorBeanDefinition);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,111 @@
|
|||||||
|
/*
|
||||||
|
* 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.polaris.circuitbreaker.resttemplate;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.lang.reflect.Method;
|
||||||
|
|
||||||
|
import com.tencent.cloud.rpc.enhancement.resttemplate.EnhancedRestTemplateReporter;
|
||||||
|
import com.tencent.polaris.api.pojo.CircuitBreakerStatus;
|
||||||
|
import com.tencent.polaris.circuitbreak.client.exception.CallAbortedException;
|
||||||
|
|
||||||
|
import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory;
|
||||||
|
import org.springframework.context.ApplicationContext;
|
||||||
|
import org.springframework.http.HttpRequest;
|
||||||
|
import org.springframework.http.client.ClientHttpRequestExecution;
|
||||||
|
import org.springframework.http.client.ClientHttpRequestInterceptor;
|
||||||
|
import org.springframework.http.client.ClientHttpResponse;
|
||||||
|
import org.springframework.util.ReflectionUtils;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
import org.springframework.web.client.ResponseErrorHandler;
|
||||||
|
import org.springframework.web.client.RestTemplate;
|
||||||
|
|
||||||
|
import static com.tencent.cloud.rpc.enhancement.resttemplate.EnhancedRestTemplateReporter.HEADER_HAS_ERROR;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PolarisCircuitBreakerRestTemplateInterceptor.
|
||||||
|
*
|
||||||
|
* @author sean yu
|
||||||
|
*/
|
||||||
|
public class PolarisCircuitBreakerRestTemplateInterceptor implements ClientHttpRequestInterceptor {
|
||||||
|
|
||||||
|
private final PolarisCircuitBreaker polarisCircuitBreaker;
|
||||||
|
|
||||||
|
private final ApplicationContext applicationContext;
|
||||||
|
|
||||||
|
private final CircuitBreakerFactory circuitBreakerFactory;
|
||||||
|
|
||||||
|
private final RestTemplate restTemplate;
|
||||||
|
|
||||||
|
public PolarisCircuitBreakerRestTemplateInterceptor(
|
||||||
|
PolarisCircuitBreaker polarisCircuitBreaker,
|
||||||
|
ApplicationContext applicationContext,
|
||||||
|
CircuitBreakerFactory circuitBreakerFactory,
|
||||||
|
RestTemplate restTemplate
|
||||||
|
) {
|
||||||
|
this.polarisCircuitBreaker = polarisCircuitBreaker;
|
||||||
|
this.applicationContext = applicationContext;
|
||||||
|
this.circuitBreakerFactory = circuitBreakerFactory;
|
||||||
|
this.restTemplate = restTemplate;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
|
||||||
|
return circuitBreakerFactory.create(request.getURI().getHost() + "#" + request.getURI().getPath()).run(
|
||||||
|
() -> {
|
||||||
|
try {
|
||||||
|
ClientHttpResponse response = execution.execute(request, body);
|
||||||
|
// pre handle response error
|
||||||
|
// EnhancedRestTemplateReporter always return true,
|
||||||
|
// so we need to check header set by EnhancedRestTemplateReporter
|
||||||
|
ResponseErrorHandler errorHandler = restTemplate.getErrorHandler();
|
||||||
|
boolean hasError = errorHandler.hasError(response);
|
||||||
|
if (errorHandler instanceof EnhancedRestTemplateReporter) {
|
||||||
|
hasError = Boolean.parseBoolean(response.getHeaders().getFirst(HEADER_HAS_ERROR));
|
||||||
|
}
|
||||||
|
if (hasError) {
|
||||||
|
errorHandler.handleError(request.getURI(), request.getMethod(), response);
|
||||||
|
}
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
catch (IOException e) {
|
||||||
|
throw new IllegalStateException(e);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
t -> {
|
||||||
|
if (StringUtils.hasText(polarisCircuitBreaker.fallback())) {
|
||||||
|
CircuitBreakerStatus.FallbackInfo fallbackInfo = new CircuitBreakerStatus.FallbackInfo(200, null, polarisCircuitBreaker.fallback());
|
||||||
|
return new PolarisCircuitBreakerHttpResponse(fallbackInfo);
|
||||||
|
}
|
||||||
|
if (!PolarisCircuitBreakerFallback.class.toGenericString().equals(polarisCircuitBreaker.fallbackClass().toGenericString())) {
|
||||||
|
Method method = ReflectionUtils.findMethod(PolarisCircuitBreakerFallback.class, "fallback");
|
||||||
|
PolarisCircuitBreakerFallback polarisCircuitBreakerFallback = applicationContext.getBean(polarisCircuitBreaker.fallbackClass());
|
||||||
|
return (PolarisCircuitBreakerHttpResponse) ReflectionUtils.invokeMethod(method, polarisCircuitBreakerFallback);
|
||||||
|
}
|
||||||
|
if (t instanceof CallAbortedException) {
|
||||||
|
CircuitBreakerStatus.FallbackInfo fallbackInfo = ((CallAbortedException) t).getFallbackInfo();
|
||||||
|
if (fallbackInfo != null) {
|
||||||
|
return new PolarisCircuitBreakerHttpResponse(fallbackInfo);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw new IllegalStateException(t);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,322 @@
|
|||||||
|
/*
|
||||||
|
* 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.polaris.circuitbreaker;
|
||||||
|
|
||||||
|
import java.io.BufferedReader;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.io.InputStreamReader;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.net.URISyntaxException;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
import com.google.protobuf.InvalidProtocolBufferException;
|
||||||
|
import com.google.protobuf.util.JsonFormat;
|
||||||
|
import com.tencent.cloud.polaris.circuitbreaker.config.PolarisCircuitBreakerFeignClientAutoConfiguration;
|
||||||
|
import com.tencent.cloud.polaris.circuitbreaker.resttemplate.PolarisCircuitBreaker;
|
||||||
|
import com.tencent.cloud.polaris.circuitbreaker.resttemplate.PolarisCircuitBreakerFallback;
|
||||||
|
import com.tencent.cloud.polaris.circuitbreaker.resttemplate.PolarisCircuitBreakerHttpResponse;
|
||||||
|
import com.tencent.cloud.rpc.enhancement.config.RpcEnhancementReporterProperties;
|
||||||
|
import com.tencent.cloud.rpc.enhancement.resttemplate.EnhancedRestTemplateReporter;
|
||||||
|
import com.tencent.polaris.api.core.ConsumerAPI;
|
||||||
|
import com.tencent.polaris.api.pojo.ServiceKey;
|
||||||
|
import com.tencent.polaris.circuitbreak.api.CircuitBreakAPI;
|
||||||
|
import com.tencent.polaris.circuitbreak.factory.CircuitBreakAPIFactory;
|
||||||
|
import com.tencent.polaris.client.util.Utils;
|
||||||
|
import com.tencent.polaris.specification.api.v1.fault.tolerance.CircuitBreakerProto;
|
||||||
|
import com.tencent.polaris.test.common.TestUtils;
|
||||||
|
import com.tencent.polaris.test.mock.discovery.NamingServer;
|
||||||
|
import org.junit.jupiter.api.AfterAll;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.beans.factory.annotation.Qualifier;
|
||||||
|
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||||
|
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
|
||||||
|
import org.springframework.cloud.openfeign.EnableFeignClients;
|
||||||
|
import org.springframework.context.ApplicationContext;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.http.HttpMethod;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.test.annotation.DirtiesContext;
|
||||||
|
import org.springframework.test.context.junit.jupiter.SpringExtension;
|
||||||
|
import org.springframework.test.web.client.ExpectedCount;
|
||||||
|
import org.springframework.test.web.client.MockRestServiceServer;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
import org.springframework.web.client.RestTemplate;
|
||||||
|
import org.springframework.web.util.DefaultUriBuilderFactory;
|
||||||
|
|
||||||
|
import static com.tencent.cloud.rpc.enhancement.resttemplate.EnhancedRestTemplateReporter.HEADER_HAS_ERROR;
|
||||||
|
import static com.tencent.polaris.test.common.TestUtils.SERVER_ADDRESS_ENV;
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
|
||||||
|
import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;
|
||||||
|
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
|
||||||
|
import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author sean yu
|
||||||
|
*/
|
||||||
|
@ExtendWith(SpringExtension.class)
|
||||||
|
@SpringBootTest(webEnvironment = RANDOM_PORT,
|
||||||
|
classes = PolarisCircuitBreakerIntegrationTest.TestConfig.class,
|
||||||
|
properties = {
|
||||||
|
"spring.cloud.gateway.enabled=false",
|
||||||
|
"feign.circuitbreaker.enabled=true",
|
||||||
|
"spring.cloud.polaris.namespace=default",
|
||||||
|
"spring.cloud.polaris.service=test"
|
||||||
|
})
|
||||||
|
@DirtiesContext
|
||||||
|
public class PolarisCircuitBreakerIntegrationTest {
|
||||||
|
|
||||||
|
private static final String TEST_SERVICE_NAME = "test-service-callee";
|
||||||
|
|
||||||
|
private static NamingServer namingServer;
|
||||||
|
|
||||||
|
@AfterAll
|
||||||
|
public static void afterAll() {
|
||||||
|
if (null != namingServer) {
|
||||||
|
namingServer.terminate();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
@Qualifier("defaultRestTemplate")
|
||||||
|
private RestTemplate defaultRestTemplate;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
@Qualifier("restTemplateFallbackFromPolaris")
|
||||||
|
private RestTemplate restTemplateFallbackFromPolaris;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
@Qualifier("restTemplateFallbackFromCode")
|
||||||
|
private RestTemplate restTemplateFallbackFromCode;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
@Qualifier("restTemplateFallbackFromCode2")
|
||||||
|
private RestTemplate restTemplateFallbackFromCode2;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
@Qualifier("restTemplateFallbackFromCode3")
|
||||||
|
private RestTemplate restTemplateFallbackFromCode3;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
@Qualifier("restTemplateFallbackFromCode4")
|
||||||
|
private RestTemplate restTemplateFallbackFromCode4;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private ApplicationContext applicationContext;
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testRestTemplate() throws URISyntaxException {
|
||||||
|
MockRestServiceServer mockServer = MockRestServiceServer.createServer(defaultRestTemplate);
|
||||||
|
mockServer
|
||||||
|
.expect(ExpectedCount.once(), requestTo(new URI("http://localhost:18001/example/service/b/info")))
|
||||||
|
.andExpect(method(HttpMethod.GET))
|
||||||
|
.andRespond(withStatus(HttpStatus.OK).body("OK"));
|
||||||
|
assertThat(defaultRestTemplate.getForObject("http://localhost:18001/example/service/b/info", String.class)).isEqualTo("OK");
|
||||||
|
mockServer.verify();
|
||||||
|
mockServer.reset();
|
||||||
|
HttpHeaders headers = new HttpHeaders();
|
||||||
|
headers.add(HEADER_HAS_ERROR, "true");
|
||||||
|
// no delegateHandler in EnhancedRestTemplateReporter, so this will except err
|
||||||
|
mockServer
|
||||||
|
.expect(ExpectedCount.once(), requestTo(new URI("http://localhost:18001/example/service/b/info")))
|
||||||
|
.andExpect(method(HttpMethod.GET))
|
||||||
|
.andRespond(withStatus(HttpStatus.BAD_GATEWAY).headers(headers).body("BAD_GATEWAY"));
|
||||||
|
assertThat(defaultRestTemplate.getForObject("http://localhost:18001/example/service/b/info", String.class)).isEqualTo("BAD_GATEWAY");
|
||||||
|
mockServer.verify();
|
||||||
|
mockServer.reset();
|
||||||
|
assertThat(restTemplateFallbackFromCode.getForObject("/example/service/b/info", String.class)).isEqualTo("\"this is a fallback class\"");
|
||||||
|
Utils.sleepUninterrupted(2000);
|
||||||
|
assertThat(restTemplateFallbackFromCode2.getForObject("/example/service/b/info", String.class)).isEqualTo("\"this is a fallback class\"");
|
||||||
|
Utils.sleepUninterrupted(2000);
|
||||||
|
assertThat(restTemplateFallbackFromCode3.getForEntity("/example/service/b/info", String.class).getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||||
|
Utils.sleepUninterrupted(2000);
|
||||||
|
assertThat(restTemplateFallbackFromCode4.getForObject("/example/service/b/info", String.class)).isEqualTo("fallback");
|
||||||
|
Utils.sleepUninterrupted(2000);
|
||||||
|
assertThat(restTemplateFallbackFromPolaris.getForObject("/example/service/b/info", String.class)).isEqualTo("\"fallback from polaris server\"");
|
||||||
|
// just for code coverage
|
||||||
|
PolarisCircuitBreakerHttpResponse response = ((CustomPolarisCircuitBreakerFallback) applicationContext.getBean("customPolarisCircuitBreakerFallback")).fallback();
|
||||||
|
assertThat(response.getStatusText()).isEqualTo("OK");
|
||||||
|
assertThat(response.getFallbackInfo().getCode()).isEqualTo(200);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
@EnableAutoConfiguration
|
||||||
|
@ImportAutoConfiguration({ PolarisCircuitBreakerFeignClientAutoConfiguration.class })
|
||||||
|
@EnableFeignClients
|
||||||
|
public static class TestConfig {
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
@PolarisCircuitBreaker(fallback = "fallback")
|
||||||
|
public RestTemplate defaultRestTemplate(RpcEnhancementReporterProperties properties, ConsumerAPI consumerAPI) {
|
||||||
|
RestTemplate defaultRestTemplate = new RestTemplate();
|
||||||
|
EnhancedRestTemplateReporter enhancedRestTemplateReporter = new EnhancedRestTemplateReporter(properties, consumerAPI);
|
||||||
|
defaultRestTemplate.setErrorHandler(enhancedRestTemplateReporter);
|
||||||
|
return defaultRestTemplate;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
@LoadBalanced
|
||||||
|
@PolarisCircuitBreaker
|
||||||
|
public RestTemplate restTemplateFallbackFromPolaris() {
|
||||||
|
DefaultUriBuilderFactory uriBuilderFactory = new DefaultUriBuilderFactory("http://" + TEST_SERVICE_NAME);
|
||||||
|
RestTemplate restTemplate = new RestTemplate();
|
||||||
|
restTemplate.setUriTemplateHandler(uriBuilderFactory);
|
||||||
|
return restTemplate;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
@LoadBalanced
|
||||||
|
@PolarisCircuitBreaker(fallbackClass = CustomPolarisCircuitBreakerFallback.class)
|
||||||
|
public RestTemplate restTemplateFallbackFromCode() {
|
||||||
|
DefaultUriBuilderFactory uriBuilderFactory = new DefaultUriBuilderFactory("http://" + TEST_SERVICE_NAME);
|
||||||
|
RestTemplate restTemplate = new RestTemplate();
|
||||||
|
restTemplate.setUriTemplateHandler(uriBuilderFactory);
|
||||||
|
return restTemplate;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
@LoadBalanced
|
||||||
|
@PolarisCircuitBreaker(fallbackClass = CustomPolarisCircuitBreakerFallback2.class)
|
||||||
|
public RestTemplate restTemplateFallbackFromCode2() {
|
||||||
|
DefaultUriBuilderFactory uriBuilderFactory = new DefaultUriBuilderFactory("http://" + TEST_SERVICE_NAME);
|
||||||
|
RestTemplate restTemplate = new RestTemplate();
|
||||||
|
restTemplate.setUriTemplateHandler(uriBuilderFactory);
|
||||||
|
return restTemplate;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
@LoadBalanced
|
||||||
|
@PolarisCircuitBreaker(fallbackClass = CustomPolarisCircuitBreakerFallback3.class)
|
||||||
|
public RestTemplate restTemplateFallbackFromCode3() {
|
||||||
|
DefaultUriBuilderFactory uriBuilderFactory = new DefaultUriBuilderFactory("http://" + TEST_SERVICE_NAME);
|
||||||
|
RestTemplate restTemplate = new RestTemplate();
|
||||||
|
restTemplate.setUriTemplateHandler(uriBuilderFactory);
|
||||||
|
return restTemplate;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
@LoadBalanced
|
||||||
|
@PolarisCircuitBreaker(fallback = "fallback")
|
||||||
|
public RestTemplate restTemplateFallbackFromCode4() {
|
||||||
|
DefaultUriBuilderFactory uriBuilderFactory = new DefaultUriBuilderFactory("http://" + TEST_SERVICE_NAME);
|
||||||
|
RestTemplate restTemplate = new RestTemplate();
|
||||||
|
restTemplate.setUriTemplateHandler(uriBuilderFactory);
|
||||||
|
return restTemplate;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public CustomPolarisCircuitBreakerFallback customPolarisCircuitBreakerFallback() {
|
||||||
|
return new CustomPolarisCircuitBreakerFallback();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public CustomPolarisCircuitBreakerFallback2 customPolarisCircuitBreakerFallback2() {
|
||||||
|
return new CustomPolarisCircuitBreakerFallback2();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public CustomPolarisCircuitBreakerFallback3 customPolarisCircuitBreakerFallback3() {
|
||||||
|
return new CustomPolarisCircuitBreakerFallback3();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public CircuitBreakAPI circuitBreakAPI() throws InvalidProtocolBufferException {
|
||||||
|
try {
|
||||||
|
namingServer = NamingServer.startNamingServer(10081);
|
||||||
|
System.setProperty(SERVER_ADDRESS_ENV, String.format("127.0.0.1:%d", namingServer.getPort()));
|
||||||
|
}
|
||||||
|
catch (IOException e) {
|
||||||
|
|
||||||
|
}
|
||||||
|
ServiceKey serviceKey = new ServiceKey("default", TEST_SERVICE_NAME);
|
||||||
|
|
||||||
|
CircuitBreakerProto.CircuitBreakerRule.Builder circuitBreakerRuleBuilder = CircuitBreakerProto.CircuitBreakerRule.newBuilder();
|
||||||
|
InputStream inputStream = PolarisCircuitBreakerMockServerTest.class.getClassLoader().getResourceAsStream("circuitBreakerRule.json");
|
||||||
|
String json = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)).lines().collect(Collectors.joining(""));
|
||||||
|
JsonFormat.parser().ignoringUnknownFields().merge(json, circuitBreakerRuleBuilder);
|
||||||
|
CircuitBreakerProto.CircuitBreakerRule circuitBreakerRule = circuitBreakerRuleBuilder.build();
|
||||||
|
CircuitBreakerProto.CircuitBreaker circuitBreaker = CircuitBreakerProto.CircuitBreaker.newBuilder().addRules(circuitBreakerRule).build();
|
||||||
|
namingServer.getNamingService().setCircuitBreaker(serviceKey, circuitBreaker);
|
||||||
|
com.tencent.polaris.api.config.Configuration configuration = TestUtils.configWithEnvAddress();
|
||||||
|
return CircuitBreakAPIFactory.createCircuitBreakAPIByConfig(configuration);
|
||||||
|
}
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/example/service/b")
|
||||||
|
public class ServiceBController {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get service information.
|
||||||
|
*
|
||||||
|
* @return service information
|
||||||
|
*/
|
||||||
|
@GetMapping("/info")
|
||||||
|
public String info() {
|
||||||
|
return "hello world ! I'm a service B1";
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class CustomPolarisCircuitBreakerFallback implements PolarisCircuitBreakerFallback {
|
||||||
|
@Override
|
||||||
|
public PolarisCircuitBreakerHttpResponse fallback() {
|
||||||
|
return new PolarisCircuitBreakerHttpResponse(
|
||||||
|
200,
|
||||||
|
new HashMap<String, String>() {{
|
||||||
|
put("xxx", "xxx");
|
||||||
|
}},
|
||||||
|
"\"this is a fallback class\"");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class CustomPolarisCircuitBreakerFallback2 implements PolarisCircuitBreakerFallback {
|
||||||
|
@Override
|
||||||
|
public PolarisCircuitBreakerHttpResponse fallback() {
|
||||||
|
return new PolarisCircuitBreakerHttpResponse(
|
||||||
|
200,
|
||||||
|
"\"this is a fallback class\""
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class CustomPolarisCircuitBreakerFallback3 implements PolarisCircuitBreakerFallback {
|
||||||
|
@Override
|
||||||
|
public PolarisCircuitBreakerHttpResponse fallback() {
|
||||||
|
return new PolarisCircuitBreakerHttpResponse(
|
||||||
|
200
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,59 @@
|
|||||||
|
{
|
||||||
|
"@type": "type.googleapis.com/v1.CircuitBreakerRule",
|
||||||
|
"id": "5f1601f01823474d9be39c0bbb26ab87",
|
||||||
|
"name": "test",
|
||||||
|
"namespace": "TestCircuitBreakerRule",
|
||||||
|
"enable": true,
|
||||||
|
"revision": "10b120c08706429f8fdc3fb44a53224b",
|
||||||
|
"ctime": "1754-08-31 06:49:24",
|
||||||
|
"mtime": "2023-02-21 17:35:31",
|
||||||
|
"etime": "",
|
||||||
|
"description": "",
|
||||||
|
"level": "METHOD",
|
||||||
|
"ruleMatcher": {
|
||||||
|
"source": {
|
||||||
|
"service": "*",
|
||||||
|
"namespace": "*"
|
||||||
|
},
|
||||||
|
"destination": {
|
||||||
|
"service": "*",
|
||||||
|
"namespace": "*",
|
||||||
|
"method": {"type": "REGEX", "value": "*"}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"errorConditions": [
|
||||||
|
{
|
||||||
|
"inputType": "RET_CODE",
|
||||||
|
"condition": {
|
||||||
|
"type": "NOT_EQUALS",
|
||||||
|
"value": "200",
|
||||||
|
"valueType": "TEXT"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"triggerCondition": [
|
||||||
|
{
|
||||||
|
"triggerType": "CONSECUTIVE_ERROR",
|
||||||
|
"errorCount": 1,
|
||||||
|
"errorPercent": 1,
|
||||||
|
"interval": 5,
|
||||||
|
"minimumRequest": 5
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"maxEjectionPercent": 0,
|
||||||
|
"recoverCondition": {
|
||||||
|
"sleepWindow": 60,
|
||||||
|
"consecutiveSuccess": 3
|
||||||
|
},
|
||||||
|
"faultDetectConfig": {
|
||||||
|
"enable": true
|
||||||
|
},
|
||||||
|
"fallbackConfig": {
|
||||||
|
"enable": true,
|
||||||
|
"response": {
|
||||||
|
"code": 200,
|
||||||
|
"headers": [{"key": "xxx", "value": "xxx"}],
|
||||||
|
"body": "\"fallback from polaris server\""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,123 @@
|
|||||||
|
/*
|
||||||
|
* 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.polaris.ratelimit.resolver;
|
||||||
|
|
||||||
|
import java.net.InetSocketAddress;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
|
||||||
|
import com.tencent.cloud.common.metadata.MetadataContextHolder;
|
||||||
|
import com.tencent.cloud.polaris.context.ServiceRuleManager;
|
||||||
|
import com.tencent.cloud.polaris.ratelimit.spi.PolarisRateLimiterLabelReactiveResolver;
|
||||||
|
import com.tencent.polaris.ratelimit.api.rpc.Argument;
|
||||||
|
import com.tencent.polaris.specification.api.v1.traffic.manage.RateLimitProto;
|
||||||
|
import org.apache.commons.lang.StringUtils;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
import org.springframework.util.CollectionUtils;
|
||||||
|
import org.springframework.web.server.ServerWebExchange;
|
||||||
|
|
||||||
|
import static com.tencent.cloud.common.constant.MetadataConstant.DefaultMetadata.DEFAULT_METADATA_SOURCE_SERVICE_NAME;
|
||||||
|
import static com.tencent.cloud.common.constant.MetadataConstant.DefaultMetadata.DEFAULT_METADATA_SOURCE_SERVICE_NAMESPACE;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* resolve arguments from rate limit rule for Reactive.
|
||||||
|
*
|
||||||
|
* @author seansyyu 2023-03-09
|
||||||
|
*/
|
||||||
|
public class RateLimitRuleArgumentReactiveResolver {
|
||||||
|
|
||||||
|
private static final Logger LOG = LoggerFactory.getLogger(RateLimitRuleArgumentReactiveResolver.class);
|
||||||
|
|
||||||
|
private final ServiceRuleManager serviceRuleManager;
|
||||||
|
|
||||||
|
private final PolarisRateLimiterLabelReactiveResolver labelResolver;
|
||||||
|
|
||||||
|
public RateLimitRuleArgumentReactiveResolver(ServiceRuleManager serviceRuleManager, PolarisRateLimiterLabelReactiveResolver labelResolver) {
|
||||||
|
this.serviceRuleManager = serviceRuleManager;
|
||||||
|
this.labelResolver = labelResolver;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Set<Argument> getArguments(ServerWebExchange request, String namespace, String service) {
|
||||||
|
RateLimitProto.RateLimit rateLimitRule = serviceRuleManager.getServiceRateLimitRule(namespace, service);
|
||||||
|
if (rateLimitRule == null) {
|
||||||
|
return Collections.emptySet();
|
||||||
|
}
|
||||||
|
List<RateLimitProto.Rule> rules = rateLimitRule.getRulesList();
|
||||||
|
if (CollectionUtils.isEmpty(rules)) {
|
||||||
|
return Collections.emptySet();
|
||||||
|
}
|
||||||
|
return rules.stream()
|
||||||
|
.flatMap(rule -> rule.getArgumentsList().stream())
|
||||||
|
.map(matchArgument -> {
|
||||||
|
String matchKey = matchArgument.getKey();
|
||||||
|
Argument argument = null;
|
||||||
|
switch (matchArgument.getType()) {
|
||||||
|
case CUSTOM:
|
||||||
|
argument = StringUtils.isBlank(matchKey) ? null :
|
||||||
|
Argument.buildCustom(matchKey, Optional.ofNullable(getCustomResolvedLabels(request).get(matchKey)).orElse(StringUtils.EMPTY));
|
||||||
|
break;
|
||||||
|
case METHOD:
|
||||||
|
argument = Argument.buildMethod(request.getRequest().getMethodValue());
|
||||||
|
break;
|
||||||
|
case HEADER:
|
||||||
|
argument = StringUtils.isBlank(matchKey) ? null :
|
||||||
|
Argument.buildHeader(matchKey, Optional.ofNullable(request.getRequest().getHeaders().getFirst(matchKey)).orElse(StringUtils.EMPTY));
|
||||||
|
break;
|
||||||
|
case QUERY:
|
||||||
|
argument = StringUtils.isBlank(matchKey) ? null :
|
||||||
|
Argument.buildQuery(matchKey, Optional.ofNullable(request.getRequest().getQueryParams().getFirst(matchKey)).orElse(StringUtils.EMPTY));
|
||||||
|
break;
|
||||||
|
case CALLER_SERVICE:
|
||||||
|
String sourceServiceNamespace = MetadataContextHolder.getDisposableMetadata(DEFAULT_METADATA_SOURCE_SERVICE_NAMESPACE, true).orElse(StringUtils.EMPTY);
|
||||||
|
String sourceServiceName = MetadataContextHolder.getDisposableMetadata(DEFAULT_METADATA_SOURCE_SERVICE_NAME, true).orElse(StringUtils.EMPTY);
|
||||||
|
if (!StringUtils.isEmpty(sourceServiceNamespace) && !StringUtils.isEmpty(sourceServiceName)) {
|
||||||
|
argument = Argument.buildCallerService(sourceServiceNamespace, sourceServiceName);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case CALLER_IP:
|
||||||
|
InetSocketAddress remoteAddress = request.getRequest().getRemoteAddress();
|
||||||
|
argument = Argument.buildCallerIP(remoteAddress != null ? remoteAddress.getAddress().getHostAddress() : StringUtils.EMPTY);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
return argument;
|
||||||
|
}).filter(Objects::nonNull).collect(Collectors.toSet());
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String, String> getCustomResolvedLabels(ServerWebExchange request) {
|
||||||
|
if (labelResolver != null) {
|
||||||
|
try {
|
||||||
|
return labelResolver.resolve(request);
|
||||||
|
}
|
||||||
|
catch (Throwable e) {
|
||||||
|
LOG.error("resolve custom label failed. resolver = {}", labelResolver.getClass().getName(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Collections.emptyMap();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,122 @@
|
|||||||
|
/*
|
||||||
|
* 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.polaris.ratelimit.resolver;
|
||||||
|
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
import com.tencent.cloud.common.metadata.MetadataContextHolder;
|
||||||
|
import com.tencent.cloud.polaris.context.ServiceRuleManager;
|
||||||
|
import com.tencent.cloud.polaris.ratelimit.filter.QuotaCheckServletFilter;
|
||||||
|
import com.tencent.cloud.polaris.ratelimit.spi.PolarisRateLimiterLabelServletResolver;
|
||||||
|
import com.tencent.polaris.ratelimit.api.rpc.Argument;
|
||||||
|
import com.tencent.polaris.specification.api.v1.traffic.manage.RateLimitProto;
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import org.apache.commons.lang.StringUtils;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
import org.springframework.util.CollectionUtils;
|
||||||
|
|
||||||
|
import static com.tencent.cloud.common.constant.MetadataConstant.DefaultMetadata.DEFAULT_METADATA_SOURCE_SERVICE_NAME;
|
||||||
|
import static com.tencent.cloud.common.constant.MetadataConstant.DefaultMetadata.DEFAULT_METADATA_SOURCE_SERVICE_NAMESPACE;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* resolve arguments from rate limit rule for Servlet.
|
||||||
|
*
|
||||||
|
* @author seansyyu 2023-03-09
|
||||||
|
*/
|
||||||
|
public class RateLimitRuleArgumentServletResolver {
|
||||||
|
|
||||||
|
private static final Logger LOG = LoggerFactory.getLogger(QuotaCheckServletFilter.class);
|
||||||
|
|
||||||
|
private final ServiceRuleManager serviceRuleManager;
|
||||||
|
|
||||||
|
private final PolarisRateLimiterLabelServletResolver labelResolver;
|
||||||
|
|
||||||
|
public RateLimitRuleArgumentServletResolver(ServiceRuleManager serviceRuleManager, PolarisRateLimiterLabelServletResolver labelResolver) {
|
||||||
|
this.serviceRuleManager = serviceRuleManager;
|
||||||
|
this.labelResolver = labelResolver;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Set<Argument> getArguments(HttpServletRequest request, String namespace, String service) {
|
||||||
|
RateLimitProto.RateLimit rateLimitRule = serviceRuleManager.getServiceRateLimitRule(namespace, service);
|
||||||
|
if (rateLimitRule == null) {
|
||||||
|
return Collections.emptySet();
|
||||||
|
}
|
||||||
|
List<RateLimitProto.Rule> rules = rateLimitRule.getRulesList();
|
||||||
|
if (CollectionUtils.isEmpty(rules)) {
|
||||||
|
return Collections.emptySet();
|
||||||
|
}
|
||||||
|
return rules.stream()
|
||||||
|
.flatMap(rule -> rule.getArgumentsList().stream())
|
||||||
|
.map(matchArgument -> {
|
||||||
|
String matchKey = matchArgument.getKey();
|
||||||
|
Argument argument = null;
|
||||||
|
switch (matchArgument.getType()) {
|
||||||
|
case CUSTOM:
|
||||||
|
argument = StringUtils.isBlank(matchKey) ? null :
|
||||||
|
Argument.buildCustom(matchKey, Optional.ofNullable(getCustomResolvedLabels(request).get(matchKey)).orElse(StringUtils.EMPTY));
|
||||||
|
break;
|
||||||
|
case METHOD:
|
||||||
|
argument = Argument.buildMethod(request.getMethod());
|
||||||
|
break;
|
||||||
|
case HEADER:
|
||||||
|
argument = StringUtils.isBlank(matchKey) ? null :
|
||||||
|
Argument.buildHeader(matchKey, Optional.ofNullable(request.getHeader(matchKey)).orElse(StringUtils.EMPTY));
|
||||||
|
break;
|
||||||
|
case QUERY:
|
||||||
|
argument = StringUtils.isBlank(matchKey) ? null :
|
||||||
|
Argument.buildQuery(matchKey, Optional.ofNullable(request.getParameter(matchKey)).orElse(StringUtils.EMPTY));
|
||||||
|
break;
|
||||||
|
case CALLER_SERVICE:
|
||||||
|
String sourceServiceNamespace = MetadataContextHolder.getDisposableMetadata(DEFAULT_METADATA_SOURCE_SERVICE_NAMESPACE, true).orElse(StringUtils.EMPTY);
|
||||||
|
String sourceServiceName = MetadataContextHolder.getDisposableMetadata(DEFAULT_METADATA_SOURCE_SERVICE_NAME, true).orElse(StringUtils.EMPTY);
|
||||||
|
if (!StringUtils.isEmpty(sourceServiceNamespace) && !StringUtils.isEmpty(sourceServiceName)) {
|
||||||
|
argument = Argument.buildCallerService(sourceServiceNamespace, sourceServiceName);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case CALLER_IP:
|
||||||
|
argument = Argument.buildCallerIP(Optional.ofNullable(request.getRemoteAddr()).orElse(StringUtils.EMPTY));
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
return argument;
|
||||||
|
}).filter(Objects::nonNull).collect(Collectors.toSet());
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String, String> getCustomResolvedLabels(HttpServletRequest request) {
|
||||||
|
if (labelResolver != null) {
|
||||||
|
try {
|
||||||
|
return labelResolver.resolve(request);
|
||||||
|
}
|
||||||
|
catch (Throwable e) {
|
||||||
|
LOG.error("resolve custom label failed. resolver = {}", labelResolver.getClass().getName(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Collections.emptyMap();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,144 @@
|
|||||||
|
/*
|
||||||
|
* 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.polaris.ratelimit.resolver;
|
||||||
|
|
||||||
|
import java.io.BufferedReader;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.io.InputStreamReader;
|
||||||
|
import java.net.InetSocketAddress;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
import com.google.protobuf.InvalidProtocolBufferException;
|
||||||
|
import com.google.protobuf.util.JsonFormat;
|
||||||
|
import com.tencent.cloud.common.metadata.MetadataContext;
|
||||||
|
import com.tencent.cloud.common.metadata.MetadataContextHolder;
|
||||||
|
import com.tencent.cloud.polaris.context.ServiceRuleManager;
|
||||||
|
import com.tencent.cloud.polaris.ratelimit.filter.QuotaCheckServletFilterTest;
|
||||||
|
import com.tencent.cloud.polaris.ratelimit.spi.PolarisRateLimiterLabelReactiveResolver;
|
||||||
|
import com.tencent.polaris.ratelimit.api.rpc.Argument;
|
||||||
|
import com.tencent.polaris.specification.api.v1.traffic.manage.RateLimitProto;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
|
||||||
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
|
||||||
|
import org.springframework.mock.web.server.MockServerWebExchange;
|
||||||
|
import org.springframework.test.context.junit.jupiter.SpringExtension;
|
||||||
|
import org.springframework.web.server.ServerWebExchange;
|
||||||
|
|
||||||
|
import static com.tencent.cloud.common.constant.MetadataConstant.DefaultMetadata.DEFAULT_METADATA_SOURCE_SERVICE_NAME;
|
||||||
|
import static com.tencent.cloud.common.constant.MetadataConstant.DefaultMetadata.DEFAULT_METADATA_SOURCE_SERVICE_NAMESPACE;
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.mockito.ArgumentMatchers.anyString;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
@ExtendWith(SpringExtension.class)
|
||||||
|
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
|
||||||
|
classes = RateLimitRuleArgumentReactiveResolverTest.TestApplication.class,
|
||||||
|
properties = {
|
||||||
|
"spring.cloud.polaris.namespace=Test", "spring.cloud.polaris.service=TestApp"
|
||||||
|
})
|
||||||
|
public class RateLimitRuleArgumentReactiveResolverTest {
|
||||||
|
|
||||||
|
private final PolarisRateLimiterLabelReactiveResolver labelResolver =
|
||||||
|
exchange -> Collections.singletonMap("xxx", "xxx");
|
||||||
|
|
||||||
|
private final PolarisRateLimiterLabelReactiveResolver labelResolverEx =
|
||||||
|
exchange -> {
|
||||||
|
throw new RuntimeException();
|
||||||
|
};
|
||||||
|
|
||||||
|
private RateLimitRuleArgumentReactiveResolver rateLimitRuleArgumentReactiveResolver1;
|
||||||
|
private RateLimitRuleArgumentReactiveResolver rateLimitRuleArgumentReactiveResolver2;
|
||||||
|
private RateLimitRuleArgumentReactiveResolver rateLimitRuleArgumentReactiveResolver3;
|
||||||
|
private RateLimitRuleArgumentReactiveResolver rateLimitRuleArgumentReactiveResolver4;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() throws InvalidProtocolBufferException {
|
||||||
|
MetadataContext.LOCAL_NAMESPACE = "TEST";
|
||||||
|
|
||||||
|
ServiceRuleManager serviceRuleManager = mock(ServiceRuleManager.class);
|
||||||
|
|
||||||
|
RateLimitProto.Rule.Builder ratelimitRuleBuilder = RateLimitProto.Rule.newBuilder();
|
||||||
|
InputStream inputStream = QuotaCheckServletFilterTest.class.getClassLoader().getResourceAsStream("ratelimit.json");
|
||||||
|
String json = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)).lines().collect(Collectors.joining(""));
|
||||||
|
JsonFormat.parser().ignoringUnknownFields().merge(json, ratelimitRuleBuilder);
|
||||||
|
RateLimitProto.Rule rateLimitRule = ratelimitRuleBuilder.build();
|
||||||
|
RateLimitProto.RateLimit rateLimit = RateLimitProto.RateLimit.newBuilder().addRules(rateLimitRule).build();
|
||||||
|
when(serviceRuleManager.getServiceRateLimitRule(anyString(), anyString())).thenReturn(rateLimit);
|
||||||
|
|
||||||
|
// normal
|
||||||
|
this.rateLimitRuleArgumentReactiveResolver1 = new RateLimitRuleArgumentReactiveResolver(serviceRuleManager, labelResolver);
|
||||||
|
// ex
|
||||||
|
this.rateLimitRuleArgumentReactiveResolver2 = new RateLimitRuleArgumentReactiveResolver(serviceRuleManager, labelResolverEx);
|
||||||
|
// null
|
||||||
|
ServiceRuleManager serviceRuleManager1 = mock(ServiceRuleManager.class);
|
||||||
|
when(serviceRuleManager1.getServiceRateLimitRule(anyString(), anyString())).thenReturn(null);
|
||||||
|
this.rateLimitRuleArgumentReactiveResolver3 = new RateLimitRuleArgumentReactiveResolver(serviceRuleManager1, labelResolver);
|
||||||
|
// null 2
|
||||||
|
ServiceRuleManager serviceRuleManager2 = mock(ServiceRuleManager.class);
|
||||||
|
RateLimitProto.RateLimit rateLimit2 = RateLimitProto.RateLimit.newBuilder().build();
|
||||||
|
when(serviceRuleManager2.getServiceRateLimitRule(anyString(), anyString())).thenReturn(rateLimit2);
|
||||||
|
this.rateLimitRuleArgumentReactiveResolver4 = new RateLimitRuleArgumentReactiveResolver(serviceRuleManager2, labelResolver);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testGetRuleArguments() {
|
||||||
|
// Mock request
|
||||||
|
MetadataContext.LOCAL_SERVICE = "Test";
|
||||||
|
// Mock request
|
||||||
|
MockServerHttpRequest request = MockServerHttpRequest.get("http://127.0.0.1:8080/test")
|
||||||
|
.remoteAddress(new InetSocketAddress("127.0.0.1", 8080))
|
||||||
|
.header("xxx", "xxx")
|
||||||
|
.queryParam("yyy", "yyy")
|
||||||
|
.build();
|
||||||
|
ServerWebExchange exchange = MockServerWebExchange.from(request);
|
||||||
|
MetadataContext metadataContext = new MetadataContext();
|
||||||
|
metadataContext.setUpstreamDisposableMetadata(new HashMap<String, String>() {{
|
||||||
|
put(DEFAULT_METADATA_SOURCE_SERVICE_NAMESPACE, MetadataContext.LOCAL_NAMESPACE);
|
||||||
|
put(DEFAULT_METADATA_SOURCE_SERVICE_NAME, MetadataContext.LOCAL_SERVICE);
|
||||||
|
}});
|
||||||
|
MetadataContextHolder.set(metadataContext);
|
||||||
|
Set<Argument> arguments = rateLimitRuleArgumentReactiveResolver1.getArguments(exchange, MetadataContext.LOCAL_NAMESPACE, MetadataContext.LOCAL_SERVICE);
|
||||||
|
Set<Argument> exceptRes = new HashSet<>();
|
||||||
|
exceptRes.add(Argument.buildMethod("GET"));
|
||||||
|
exceptRes.add(Argument.buildHeader("xxx", "xxx"));
|
||||||
|
exceptRes.add(Argument.buildQuery("yyy", "yyy"));
|
||||||
|
exceptRes.add(Argument.buildCallerIP("127.0.0.1"));
|
||||||
|
exceptRes.add(Argument.buildCustom("xxx", "xxx"));
|
||||||
|
exceptRes.add(Argument.buildCallerService(MetadataContext.LOCAL_NAMESPACE, MetadataContext.LOCAL_SERVICE));
|
||||||
|
assertThat(arguments).isEqualTo(exceptRes);
|
||||||
|
|
||||||
|
rateLimitRuleArgumentReactiveResolver2.getArguments(exchange, MetadataContext.LOCAL_NAMESPACE, MetadataContext.LOCAL_SERVICE);
|
||||||
|
rateLimitRuleArgumentReactiveResolver3.getArguments(exchange, MetadataContext.LOCAL_NAMESPACE, MetadataContext.LOCAL_SERVICE);
|
||||||
|
rateLimitRuleArgumentReactiveResolver4.getArguments(exchange, MetadataContext.LOCAL_NAMESPACE, MetadataContext.LOCAL_SERVICE);
|
||||||
|
}
|
||||||
|
|
||||||
|
@SpringBootApplication
|
||||||
|
protected static class TestApplication {
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,135 @@
|
|||||||
|
/*
|
||||||
|
* 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.polaris.ratelimit.resolver;
|
||||||
|
|
||||||
|
import java.io.BufferedReader;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.io.InputStreamReader;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
import com.google.protobuf.InvalidProtocolBufferException;
|
||||||
|
import com.google.protobuf.util.JsonFormat;
|
||||||
|
import com.tencent.cloud.common.metadata.MetadataContext;
|
||||||
|
import com.tencent.cloud.common.metadata.MetadataContextHolder;
|
||||||
|
import com.tencent.cloud.polaris.context.ServiceRuleManager;
|
||||||
|
import com.tencent.cloud.polaris.ratelimit.filter.QuotaCheckServletFilterTest;
|
||||||
|
import com.tencent.cloud.polaris.ratelimit.spi.PolarisRateLimiterLabelServletResolver;
|
||||||
|
import com.tencent.polaris.ratelimit.api.rpc.Argument;
|
||||||
|
import com.tencent.polaris.specification.api.v1.traffic.manage.RateLimitProto;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
|
||||||
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.mock.web.MockHttpServletRequest;
|
||||||
|
import org.springframework.test.context.junit.jupiter.SpringExtension;
|
||||||
|
|
||||||
|
import static com.tencent.cloud.common.constant.MetadataConstant.DefaultMetadata.DEFAULT_METADATA_SOURCE_SERVICE_NAME;
|
||||||
|
import static com.tencent.cloud.common.constant.MetadataConstant.DefaultMetadata.DEFAULT_METADATA_SOURCE_SERVICE_NAMESPACE;
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.mockito.ArgumentMatchers.anyString;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
@ExtendWith(SpringExtension.class)
|
||||||
|
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
|
||||||
|
classes = RateLimitRuleArgumentServletResolverTest.TestApplication.class,
|
||||||
|
properties = {
|
||||||
|
"spring.cloud.polaris.namespace=Test", "spring.cloud.polaris.service=TestApp"
|
||||||
|
})
|
||||||
|
public class RateLimitRuleArgumentServletResolverTest {
|
||||||
|
|
||||||
|
private final PolarisRateLimiterLabelServletResolver labelResolver =
|
||||||
|
exchange -> Collections.singletonMap("xxx", "xxx");
|
||||||
|
private final PolarisRateLimiterLabelServletResolver labelResolverEx =
|
||||||
|
exchange -> {
|
||||||
|
throw new RuntimeException();
|
||||||
|
};
|
||||||
|
|
||||||
|
private RateLimitRuleArgumentServletResolver rateLimitRuleArgumentServletResolver1;
|
||||||
|
private RateLimitRuleArgumentServletResolver rateLimitRuleArgumentServletResolver2;
|
||||||
|
private RateLimitRuleArgumentServletResolver rateLimitRuleArgumentServletResolver3;
|
||||||
|
private RateLimitRuleArgumentServletResolver rateLimitRuleArgumentServletResolver4;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() throws InvalidProtocolBufferException {
|
||||||
|
MetadataContext.LOCAL_NAMESPACE = "TEST";
|
||||||
|
|
||||||
|
ServiceRuleManager serviceRuleManager = mock(ServiceRuleManager.class);
|
||||||
|
|
||||||
|
RateLimitProto.Rule.Builder ratelimitRuleBuilder = RateLimitProto.Rule.newBuilder();
|
||||||
|
InputStream inputStream = QuotaCheckServletFilterTest.class.getClassLoader().getResourceAsStream("ratelimit.json");
|
||||||
|
String json = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)).lines().collect(Collectors.joining(""));
|
||||||
|
JsonFormat.parser().ignoringUnknownFields().merge(json, ratelimitRuleBuilder);
|
||||||
|
RateLimitProto.Rule rateLimitRule = ratelimitRuleBuilder.build();
|
||||||
|
RateLimitProto.RateLimit rateLimit = RateLimitProto.RateLimit.newBuilder().addRules(rateLimitRule).build();
|
||||||
|
when(serviceRuleManager.getServiceRateLimitRule(anyString(), anyString())).thenReturn(rateLimit);
|
||||||
|
|
||||||
|
// normal
|
||||||
|
this.rateLimitRuleArgumentServletResolver1 = new RateLimitRuleArgumentServletResolver(serviceRuleManager, labelResolver);
|
||||||
|
// ex
|
||||||
|
this.rateLimitRuleArgumentServletResolver2 = new RateLimitRuleArgumentServletResolver(serviceRuleManager, labelResolverEx);
|
||||||
|
// null
|
||||||
|
ServiceRuleManager serviceRuleManager1 = mock(ServiceRuleManager.class);
|
||||||
|
when(serviceRuleManager1.getServiceRateLimitRule(anyString(), anyString())).thenReturn(null);
|
||||||
|
this.rateLimitRuleArgumentServletResolver3 = new RateLimitRuleArgumentServletResolver(serviceRuleManager1, labelResolver);
|
||||||
|
// null 2
|
||||||
|
ServiceRuleManager serviceRuleManager2 = mock(ServiceRuleManager.class);
|
||||||
|
RateLimitProto.RateLimit rateLimit2 = RateLimitProto.RateLimit.newBuilder().build();
|
||||||
|
when(serviceRuleManager2.getServiceRateLimitRule(anyString(), anyString())).thenReturn(rateLimit2);
|
||||||
|
this.rateLimitRuleArgumentServletResolver4 = new RateLimitRuleArgumentServletResolver(serviceRuleManager2, labelResolver);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testGetRuleArguments() {
|
||||||
|
// Mock request
|
||||||
|
MetadataContext.LOCAL_SERVICE = "Test";
|
||||||
|
MockHttpServletRequest request = new MockHttpServletRequest(null, "GET", "/xxx");
|
||||||
|
request.setParameter("yyy", "yyy");
|
||||||
|
request.addHeader("xxx", "xxx");
|
||||||
|
MetadataContext metadataContext = new MetadataContext();
|
||||||
|
metadataContext.setUpstreamDisposableMetadata(new HashMap<String, String>() {{
|
||||||
|
put(DEFAULT_METADATA_SOURCE_SERVICE_NAMESPACE, MetadataContext.LOCAL_NAMESPACE);
|
||||||
|
put(DEFAULT_METADATA_SOURCE_SERVICE_NAME, MetadataContext.LOCAL_SERVICE);
|
||||||
|
}});
|
||||||
|
MetadataContextHolder.set(metadataContext);
|
||||||
|
Set<Argument> arguments = rateLimitRuleArgumentServletResolver1.getArguments(request, MetadataContext.LOCAL_NAMESPACE, MetadataContext.LOCAL_SERVICE);
|
||||||
|
Set<Argument> exceptRes = new HashSet<>();
|
||||||
|
exceptRes.add(Argument.buildMethod("GET"));
|
||||||
|
exceptRes.add(Argument.buildHeader("xxx", "xxx"));
|
||||||
|
exceptRes.add(Argument.buildQuery("yyy", "yyy"));
|
||||||
|
exceptRes.add(Argument.buildCallerIP("127.0.0.1"));
|
||||||
|
exceptRes.add(Argument.buildCustom("xxx", "xxx"));
|
||||||
|
exceptRes.add(Argument.buildCallerService(MetadataContext.LOCAL_NAMESPACE, MetadataContext.LOCAL_SERVICE));
|
||||||
|
assertThat(arguments).isEqualTo(exceptRes);
|
||||||
|
|
||||||
|
rateLimitRuleArgumentServletResolver2.getArguments(request, MetadataContext.LOCAL_NAMESPACE, MetadataContext.LOCAL_SERVICE);
|
||||||
|
rateLimitRuleArgumentServletResolver3.getArguments(request, MetadataContext.LOCAL_NAMESPACE, MetadataContext.LOCAL_SERVICE);
|
||||||
|
rateLimitRuleArgumentServletResolver4.getArguments(request, MetadataContext.LOCAL_NAMESPACE, MetadataContext.LOCAL_SERVICE);
|
||||||
|
}
|
||||||
|
|
||||||
|
@SpringBootApplication
|
||||||
|
protected static class TestApplication {
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,95 @@
|
|||||||
|
{
|
||||||
|
"id": "f7560cce829e4d4c8556a6be63539af5",
|
||||||
|
"service": "xxx",
|
||||||
|
"namespace": "default",
|
||||||
|
"subset": {},
|
||||||
|
"priority": 0,
|
||||||
|
"resource": "QPS",
|
||||||
|
"type": "GLOBAL",
|
||||||
|
"labels": {},
|
||||||
|
"amounts": [
|
||||||
|
{
|
||||||
|
"maxAmount": 1,
|
||||||
|
"validDuration": "1s",
|
||||||
|
"precision": null,
|
||||||
|
"startAmount": null,
|
||||||
|
"minAmount": null
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"action": "REJECT",
|
||||||
|
"disable": false,
|
||||||
|
"report": null,
|
||||||
|
"ctime": "2022-12-11 21:56:59",
|
||||||
|
"mtime": "2023-03-10 15:40:33",
|
||||||
|
"revision": "6eec6f416bee40ecbf664c93add61358",
|
||||||
|
"service_token": null,
|
||||||
|
"adjuster": null,
|
||||||
|
"regex_combine": true,
|
||||||
|
"amountMode": "GLOBAL_TOTAL",
|
||||||
|
"failover": "FAILOVER_LOCAL",
|
||||||
|
"cluster": null,
|
||||||
|
"method": {
|
||||||
|
"type": "EXACT",
|
||||||
|
"value": "/xxx",
|
||||||
|
"value_type": "TEXT"
|
||||||
|
},
|
||||||
|
"arguments": [
|
||||||
|
{
|
||||||
|
"type": "CALLER_SERVICE",
|
||||||
|
"key": "default",
|
||||||
|
"value": {
|
||||||
|
"type": "EXACT",
|
||||||
|
"value": "xxx",
|
||||||
|
"value_type": "TEXT"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "HEADER",
|
||||||
|
"key": "xxx",
|
||||||
|
"value": {
|
||||||
|
"type": "EXACT",
|
||||||
|
"value": "xxx",
|
||||||
|
"value_type": "TEXT"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "QUERY",
|
||||||
|
"key": "yyy",
|
||||||
|
"value": {
|
||||||
|
"type": "EXACT",
|
||||||
|
"value": "yyy",
|
||||||
|
"value_type": "TEXT"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "METHOD",
|
||||||
|
"key": "$method",
|
||||||
|
"value": {
|
||||||
|
"type": "EXACT",
|
||||||
|
"value": "GET",
|
||||||
|
"value_type": "TEXT"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "CALLER_IP",
|
||||||
|
"key": "$caller_ip",
|
||||||
|
"value": {
|
||||||
|
"type": "EXACT",
|
||||||
|
"value": "127.0.0.1",
|
||||||
|
"value_type": "TEXT"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "CUSTOM",
|
||||||
|
"key": "xxx",
|
||||||
|
"value": {
|
||||||
|
"type": "EXACT",
|
||||||
|
"value": "xxx",
|
||||||
|
"value_type": "TEXT"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"name": "xxx",
|
||||||
|
"etime": "2023-03-10 15:40:33",
|
||||||
|
"max_queue_delay": 30
|
||||||
|
}
|
@ -0,0 +1,63 @@
|
|||||||
|
/*
|
||||||
|
* 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.common.spi.impl;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
import com.tencent.cloud.common.spi.InstanceMetadataProvider;
|
||||||
|
import com.tencent.cloud.common.util.ApplicationContextAwareUtils;
|
||||||
|
|
||||||
|
import static com.tencent.cloud.common.constant.MetadataConstant.DefaultMetadata.DEFAULT_METADATA_SOURCE_SERVICE_NAME;
|
||||||
|
import static com.tencent.cloud.common.constant.MetadataConstant.DefaultMetadata.DEFAULT_METADATA_SOURCE_SERVICE_NAMESPACE;
|
||||||
|
import static com.tencent.cloud.common.metadata.MetadataContext.LOCAL_NAMESPACE;
|
||||||
|
import static com.tencent.cloud.common.metadata.MetadataContext.LOCAL_SERVICE;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* DefaultInstanceMetadataProvider.
|
||||||
|
* provide DEFAULT_METADATA_SOURCE_SERVICE_NAMESPACE, DEFAULT_METADATA_SOURCE_SERVICE_NAME
|
||||||
|
*
|
||||||
|
* @author sean yu
|
||||||
|
*/
|
||||||
|
public class DefaultInstanceMetadataProvider implements InstanceMetadataProvider {
|
||||||
|
|
||||||
|
private final ApplicationContextAwareUtils applicationContextAwareUtils;
|
||||||
|
|
||||||
|
// ensure ApplicationContextAwareUtils init before
|
||||||
|
public DefaultInstanceMetadataProvider(ApplicationContextAwareUtils applicationContextAwareUtils) {
|
||||||
|
this.applicationContextAwareUtils = applicationContextAwareUtils;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Map<String, String> getMetadata() {
|
||||||
|
return new HashMap<String, String>() {{
|
||||||
|
put(DEFAULT_METADATA_SOURCE_SERVICE_NAMESPACE, LOCAL_NAMESPACE);
|
||||||
|
put(DEFAULT_METADATA_SOURCE_SERVICE_NAME, LOCAL_SERVICE);
|
||||||
|
}};
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Set<String> getDisposableMetadataKeys() {
|
||||||
|
return new HashSet<>(Arrays.asList(DEFAULT_METADATA_SOURCE_SERVICE_NAMESPACE, DEFAULT_METADATA_SOURCE_SERVICE_NAME));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,39 @@
|
|||||||
|
/*
|
||||||
|
* 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.polaris.circuitbreaker.feign.example;
|
||||||
|
|
||||||
|
import org.springframework.cloud.openfeign.FeignClient;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ProviderBWithFallback.
|
||||||
|
*
|
||||||
|
* @author sean yu
|
||||||
|
*/
|
||||||
|
@FeignClient(name = "polaris-circuitbreaker-callee-service", contextId = "fallback-from-code", fallback = ProviderBFallback.class)
|
||||||
|
public interface ProviderBWithFallback {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get info of service B.
|
||||||
|
*
|
||||||
|
* @return info of service B
|
||||||
|
*/
|
||||||
|
@GetMapping("/example/service/b/info")
|
||||||
|
String info();
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,43 @@
|
|||||||
|
/*
|
||||||
|
* 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.polaris.circuitbreaker.resttemplate.example;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
|
||||||
|
import com.tencent.cloud.polaris.circuitbreaker.resttemplate.PolarisCircuitBreakerFallback;
|
||||||
|
import com.tencent.cloud.polaris.circuitbreaker.resttemplate.PolarisCircuitBreakerHttpResponse;
|
||||||
|
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* CustomFallback.
|
||||||
|
*
|
||||||
|
* @author sean yu
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
public class CustomFallback implements PolarisCircuitBreakerFallback {
|
||||||
|
@Override
|
||||||
|
public PolarisCircuitBreakerHttpResponse fallback() {
|
||||||
|
return new PolarisCircuitBreakerHttpResponse(
|
||||||
|
200,
|
||||||
|
new HashMap<String, String>() {{
|
||||||
|
put("Content-Type", "application/json");
|
||||||
|
}},
|
||||||
|
"{\"msg\": \"this is a fallback class\"}");
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,44 @@
|
|||||||
|
/*
|
||||||
|
* 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.callee;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import com.tencent.cloud.polaris.ratelimit.spi.PolarisRateLimiterLabelReactiveResolver;
|
||||||
|
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.web.server.ServerWebExchange;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* resolver custom label from request.
|
||||||
|
*
|
||||||
|
* @author sean yu
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
public class CustomLabelResolverReactive implements PolarisRateLimiterLabelReactiveResolver {
|
||||||
|
@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;
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in new issue