feature: improve circuit breaker usage (#913)
parent
6daa381190
commit
097dad88ee
@ -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.FeignClientFactoryBean;
|
||||||
|
import org.springframework.cloud.openfeign.FeignContext;
|
||||||
|
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, FeignContext 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, FeignContext 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, FeignContext 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, FeignContext 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,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\"}");
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in new issue