optimize report call result for restTemplate (#565)

pull/571/head
lepdou 2 years ago committed by GitHub
parent fc3986cb97
commit 7774b418e8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -32,3 +32,4 @@
- [Optimize: shutdown server when connect to config server failed](https://github.com/Tencent/spring-cloud-tencent/pull/554) - [Optimize: shutdown server when connect to config server failed](https://github.com/Tencent/spring-cloud-tencent/pull/554)
- [Report the labels in request when report the result of invocation by Feign](https://github.com/Tencent/spring-cloud-tencent/pull/556) - [Report the labels in request when report the result of invocation by Feign](https://github.com/Tencent/spring-cloud-tencent/pull/556)
- [fix:fix heartbeat interval different configuration from polaris-java SDK.](https://github.com/Tencent/spring-cloud-tencent/pull/559) - [fix:fix heartbeat interval different configuration from polaris-java SDK.](https://github.com/Tencent/spring-cloud-tencent/pull/559)
- [Optimize: optimize report call result for restTemplate.](https://github.com/Tencent/spring-cloud-tencent/pull/565)

@ -46,6 +46,11 @@ public class MetadataContext {
*/ */
public static final String FRAGMENT_DISPOSABLE = "disposable"; public static final String FRAGMENT_DISPOSABLE = "disposable";
/**
* load balancer context.
*/
public static final String FRAGMENT_LOAD_BALANCER = "loadbalancer";
/** /**
* upstream disposable Context. * upstream disposable Context.
*/ */

@ -28,6 +28,11 @@
</dependency> </dependency>
<!-- Polaris dependencies end --> <!-- Polaris dependencies end -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.cloud</groupId> <groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId> <artifactId>spring-cloud-starter-openfeign</artifactId>

@ -53,15 +53,15 @@ public abstract class AbstractPolarisReporterAdapter {
private static final List<HttpStatus> HTTP_STATUSES = toList(NOT_IMPLEMENTED, BAD_GATEWAY, private static final List<HttpStatus> HTTP_STATUSES = toList(NOT_IMPLEMENTED, BAD_GATEWAY,
SERVICE_UNAVAILABLE, GATEWAY_TIMEOUT, HTTP_VERSION_NOT_SUPPORTED, VARIANT_ALSO_NEGOTIATES, SERVICE_UNAVAILABLE, GATEWAY_TIMEOUT, HTTP_VERSION_NOT_SUPPORTED, VARIANT_ALSO_NEGOTIATES,
INSUFFICIENT_STORAGE, LOOP_DETECTED, BANDWIDTH_LIMIT_EXCEEDED, NOT_EXTENDED, NETWORK_AUTHENTICATION_REQUIRED); INSUFFICIENT_STORAGE, LOOP_DETECTED, BANDWIDTH_LIMIT_EXCEEDED, NOT_EXTENDED, NETWORK_AUTHENTICATION_REQUIRED);
protected final RpcEnhancementReporterProperties properties; protected final RpcEnhancementReporterProperties reportProperties;
/** /**
* Constructor With {@link RpcEnhancementReporterProperties} . * Constructor With {@link RpcEnhancementReporterProperties} .
* *
* @param properties instance of {@link RpcEnhancementReporterProperties}. * @param reportProperties instance of {@link RpcEnhancementReporterProperties}.
*/ */
protected AbstractPolarisReporterAdapter(RpcEnhancementReporterProperties properties) { protected AbstractPolarisReporterAdapter(RpcEnhancementReporterProperties reportProperties) {
this.properties = properties; this.reportProperties = reportProperties;
} }
/** /**
@ -88,12 +88,12 @@ public abstract class AbstractPolarisReporterAdapter {
} }
else { else {
// statuses > series // statuses > series
List<HttpStatus> status = properties.getStatuses(); List<HttpStatus> status = reportProperties.getStatuses();
if (status.isEmpty()) { if (status.isEmpty()) {
List<HttpStatus.Series> series = properties.getSeries(); List<HttpStatus.Series> series = reportProperties.getSeries();
// Check INTERNAL_SERVER_ERROR (500) status. // Check INTERNAL_SERVER_ERROR (500) status.
if (properties.isIgnoreInternalServerError() && Objects.equals(httpStatus, INTERNAL_SERVER_ERROR)) { if (reportProperties.isIgnoreInternalServerError() && Objects.equals(httpStatus, INTERNAL_SERVER_ERROR)) {
return false; return false;
} }
if (series.isEmpty()) { if (series.isEmpty()) {

@ -27,8 +27,8 @@ import com.tencent.cloud.rpc.enhancement.feign.EnhancedFeignPluginRunner;
import com.tencent.cloud.rpc.enhancement.feign.plugin.EnhancedFeignPlugin; import com.tencent.cloud.rpc.enhancement.feign.plugin.EnhancedFeignPlugin;
import com.tencent.cloud.rpc.enhancement.feign.plugin.reporter.ExceptionPolarisReporter; import com.tencent.cloud.rpc.enhancement.feign.plugin.reporter.ExceptionPolarisReporter;
import com.tencent.cloud.rpc.enhancement.feign.plugin.reporter.SuccessPolarisReporter; import com.tencent.cloud.rpc.enhancement.feign.plugin.reporter.SuccessPolarisReporter;
import com.tencent.cloud.rpc.enhancement.resttemplate.BlockingLoadBalancerClientAspect;
import com.tencent.cloud.rpc.enhancement.resttemplate.EnhancedRestTemplateReporter; import com.tencent.cloud.rpc.enhancement.resttemplate.EnhancedRestTemplateReporter;
import com.tencent.cloud.rpc.enhancement.resttemplate.PolarisResponseErrorHandler;
import com.tencent.polaris.api.core.ConsumerAPI; import com.tencent.polaris.api.core.ConsumerAPI;
import org.springframework.beans.factory.SmartInitializingSingleton; import org.springframework.beans.factory.SmartInitializingSingleton;
@ -36,6 +36,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.cloud.client.loadbalancer.LoadBalanced;
@ -107,10 +108,9 @@ public class RpcEnhancementAutoConfiguration {
private List<RestTemplate> restTemplates = Collections.emptyList(); private List<RestTemplate> restTemplates = Collections.emptyList();
@Bean @Bean
public EnhancedRestTemplateReporter polarisRestTemplateResponseErrorHandler( public EnhancedRestTemplateReporter enhancedRestTemplateReporter(
RpcEnhancementReporterProperties properties, ConsumerAPI consumerAPI, RpcEnhancementReporterProperties properties, ConsumerAPI consumerAPI) {
@Autowired(required = false) PolarisResponseErrorHandler polarisResponseErrorHandler) { return new EnhancedRestTemplateReporter(properties, consumerAPI);
return new EnhancedRestTemplateReporter(properties, consumerAPI, polarisResponseErrorHandler);
} }
@Bean @Bean
@ -121,5 +121,12 @@ public class RpcEnhancementAutoConfiguration {
} }
}; };
} }
@Bean
@ConditionalOnMissingBean
@ConditionalOnClass(name = {"org.springframework.cloud.loadbalancer.blocking.client.BlockingLoadBalancerClient"})
public BlockingLoadBalancerClientAspect blockingLoadBalancerClientAspect() {
return new BlockingLoadBalancerClientAspect();
}
} }
} }

@ -61,7 +61,7 @@ public class SuccessPolarisReporter extends AbstractPolarisReporterAdapter imple
@Override @Override
public void run(EnhancedFeignContext context) { public void run(EnhancedFeignContext context) {
if (!properties.isEnabled()) { if (!reportProperties.isEnabled()) {
return; return;
} }

@ -0,0 +1,42 @@
/*
* 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.rpc.enhancement.resttemplate;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
/**
* Intercept for LoadBalancerClient, put host&port to thread local.
* @author lepdou 2022-09-05
*/
@Aspect
public class BlockingLoadBalancerClientAspect {
@Pointcut("execution(public * org.springframework.cloud.loadbalancer.blocking.client.BlockingLoadBalancerClient.reconstructURI(..)) ")
public void pointcut() {
}
@Around("pointcut()")
public Object invoke(ProceedingJoinPoint joinPoint) throws Throwable {
LoadBalancerClientAspectUtils.extractLoadBalancerResult(joinPoint);
return joinPoint.proceed();
}
}

@ -18,13 +18,11 @@
package com.tencent.cloud.rpc.enhancement.resttemplate; package com.tencent.cloud.rpc.enhancement.resttemplate;
import java.io.IOException; import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URI; import java.net.URI;
import java.net.URL; import java.util.Map;
import java.util.Objects;
import com.tencent.cloud.common.metadata.MetadataContext; import com.tencent.cloud.common.metadata.MetadataContext;
import com.tencent.cloud.common.util.ReflectionUtils; import com.tencent.cloud.common.metadata.MetadataContextHolder;
import com.tencent.cloud.rpc.enhancement.AbstractPolarisReporterAdapter; import com.tencent.cloud.rpc.enhancement.AbstractPolarisReporterAdapter;
import com.tencent.cloud.rpc.enhancement.config.RpcEnhancementReporterProperties; import com.tencent.cloud.rpc.enhancement.config.RpcEnhancementReporterProperties;
import com.tencent.polaris.api.core.ConsumerAPI; import com.tencent.polaris.api.core.ConsumerAPI;
@ -35,6 +33,9 @@ import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.http.HttpMethod; import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpResponse; import org.springframework.http.client.ClientHttpResponse;
import org.springframework.lang.NonNull; import org.springframework.lang.NonNull;
@ -45,65 +46,125 @@ import org.springframework.web.client.ResponseErrorHandler;
* *
* @author wh 2022/6/21 * @author wh 2022/6/21
*/ */
public class EnhancedRestTemplateReporter extends AbstractPolarisReporterAdapter implements ResponseErrorHandler { public class EnhancedRestTemplateReporter extends AbstractPolarisReporterAdapter implements ResponseErrorHandler, ApplicationContextAware {
private static final Logger LOG = LoggerFactory.getLogger(EnhancedRestTemplateReporter.class); private static final Logger LOGGER = LoggerFactory.getLogger(EnhancedRestTemplateReporter.class);
private static final String FILE_NAME = "connection"; static final String HEADER_HAS_ERROR = "X-SCT-Has-Error";
private final ConsumerAPI consumerAPI; private final ConsumerAPI consumerAPI;
private ResponseErrorHandler delegateHandler;
private final PolarisResponseErrorHandler polarisResponseErrorHandler; public EnhancedRestTemplateReporter(RpcEnhancementReporterProperties properties, ConsumerAPI consumerAPI) {
public EnhancedRestTemplateReporter(RpcEnhancementReporterProperties properties, ConsumerAPI consumerAPI,
PolarisResponseErrorHandler polarisResponseErrorHandler) {
super(properties); super(properties);
this.consumerAPI = consumerAPI; this.consumerAPI = consumerAPI;
this.polarisResponseErrorHandler = polarisResponseErrorHandler;
} }
@Override @Override
public boolean hasError(@NonNull ClientHttpResponse response) { public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
String[] handlerBeanNames = applicationContext.getBeanNamesForType(ResponseErrorHandler.class);
if (handlerBeanNames.length == 1) {
return;
}
// inject user custom ResponseErrorHandler
for (String beanName : handlerBeanNames) {
// ignore self
if (StringUtils.equalsIgnoreCase("enhancedRestTemplateReporter", beanName)) {
continue;
}
this.delegateHandler = (ResponseErrorHandler) applicationContext.getBean(beanName);
}
}
@Override
public boolean hasError(@NonNull ClientHttpResponse response) throws IOException {
if (delegateHandler != null) {
// Preserve the delegated handler result
boolean hasError = delegateHandler.hasError(response);
response.getHeaders().add(HEADER_HAS_ERROR, String.valueOf(hasError));
}
return true; return true;
} }
@Override @Override
public void handleError(@NonNull ClientHttpResponse response) throws IOException { public void handleError(@NonNull ClientHttpResponse response) throws IOException {
if (Objects.nonNull(polarisResponseErrorHandler)) { if (realHasError(response)) {
if (polarisResponseErrorHandler.hasError(response)) { delegateHandler.handleError(response);
polarisResponseErrorHandler.handleError(response);
}
} }
clear(response);
} }
@Override @Override
public void handleError(@NonNull URI url, @NonNull HttpMethod method, @NonNull ClientHttpResponse response) { public void handleError(@NonNull URI url, @NonNull HttpMethod method, @NonNull ClientHttpResponse response) throws IOException {
if (!properties.isEnabled()) { // report result to polaris
return; if (reportProperties.isEnabled()) {
reportResult(url, response);
} }
// invoke delegate handler
invokeDelegateHandler(url, method, response);
}
private void reportResult(URI url, ClientHttpResponse response) {
ServiceCallResult resultRequest = createServiceCallResult(url); ServiceCallResult resultRequest = createServiceCallResult(url);
try { try {
HttpURLConnection connection = (HttpURLConnection) ReflectionUtils.getFieldValue(response, FILE_NAME); Map<String, String> loadBalancerContext = MetadataContextHolder.get()
if (connection != null) { .getFragmentContext(MetadataContext.FRAGMENT_LOAD_BALANCER);
URL realURL = connection.getURL();
resultRequest.setHost(realURL.getHost()); String targetHost = loadBalancerContext.get("host");
resultRequest.setPort(realURL.getPort()); String targetPort = loadBalancerContext.get("port");
if (StringUtils.isBlank(targetHost) || StringUtils.isBlank(targetPort)) {
LOGGER.warn("Can not get target host or port from metadata context. host = {}, port = {}", targetHost, targetPort);
return;
} }
resultRequest.setHost(targetHost);
resultRequest.setPort(Integer.parseInt(targetPort));
// checking response http status code
if (apply(response.getStatusCode())) { if (apply(response.getStatusCode())) {
resultRequest.setRetStatus(RetStatus.RetFail); resultRequest.setRetStatus(RetStatus.RetFail);
} }
// processing report with consumerAPI .
LOGGER.debug("Will report result of {}. URL=[{}]. Response=[{}].", resultRequest.getRetStatus().name(),
url, response);
consumerAPI.updateServiceCallResult(resultRequest);
} }
catch (Exception e) { catch (Exception e) {
LOG.error("Will report response of {} url {}", response, url, e); LOGGER.error("RestTemplate response reporter execute failed of {} url {}", response, url, e);
resultRequest.setRetStatus(RetStatus.RetFail);
} }
finally { }
LOG.debug("Will report result of {}. URL=[{}]. Response=[{}].", resultRequest.getRetStatus().name(),
url, response); private void invokeDelegateHandler(URI url, HttpMethod method, ClientHttpResponse response) throws IOException {
consumerAPI.updateServiceCallResult(resultRequest); if (realHasError(response)) {
delegateHandler.handleError(url, method, response);
} }
clear(response);
}
private Boolean realHasError(ClientHttpResponse response) {
if (delegateHandler == null) {
return false;
}
String hasErrorHeader = response.getHeaders().getFirst(HEADER_HAS_ERROR);
if (StringUtils.isBlank(hasErrorHeader)) {
return false;
}
return Boolean.parseBoolean(hasErrorHeader);
}
private void clear(ClientHttpResponse response) {
if (!response.getHeaders().containsKey(HEADER_HAS_ERROR)) {
return;
}
response.getHeaders().remove(HEADER_HAS_ERROR);
} }
private ServiceCallResult createServiceCallResult(URI uri) { private ServiceCallResult createServiceCallResult(URI uri) {
@ -120,4 +181,8 @@ public class EnhancedRestTemplateReporter extends AbstractPolarisReporterAdapter
} }
return resultRequest; return resultRequest;
} }
public void setDelegateHandler(ResponseErrorHandler delegateHandler) {
this.delegateHandler = delegateHandler;
}
} }

@ -0,0 +1,45 @@
/*
* 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.rpc.enhancement.resttemplate;
import com.tencent.cloud.common.metadata.MetadataContext;
import com.tencent.cloud.common.metadata.MetadataContextHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
/**
* Extract load balancer result from {@link LoadBalancerClient} and put to MetadataContext.
* @author lepdou 2022-09-06
*/
public final class LoadBalancerClientAspectUtils {
private LoadBalancerClientAspectUtils() {
}
public static void extractLoadBalancerResult(ProceedingJoinPoint joinPoint) {
Object server = joinPoint.getArgs()[0];
if (server instanceof ServiceInstance) {
ServiceInstance instance = (ServiceInstance) server;
MetadataContextHolder.get().putContext(MetadataContext.FRAGMENT_LOAD_BALANCER, "host", instance.getHost());
MetadataContextHolder.get()
.putContext(MetadataContext.FRAGMENT_LOAD_BALANCER, "port", String.valueOf(instance.getPort()));
}
}
}

@ -17,55 +17,180 @@
package com.tencent.cloud.rpc.enhancement.resttemplate; package com.tencent.cloud.rpc.enhancement.resttemplate;
import java.io.IOException;
import java.net.HttpURLConnection; import java.io.InputStream;
import java.net.URI; import java.net.URI;
import java.net.URL; import java.util.HashMap;
import java.util.Map;
import com.tencent.cloud.common.metadata.MetadataContext;
import com.tencent.cloud.common.metadata.MetadataContextHolder;
import com.tencent.cloud.common.util.ApplicationContextAwareUtils;
import com.tencent.cloud.rpc.enhancement.config.RpcEnhancementReporterProperties; import com.tencent.cloud.rpc.enhancement.config.RpcEnhancementReporterProperties;
import com.tencent.polaris.api.core.ConsumerAPI; import com.tencent.polaris.api.core.ConsumerAPI;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.http.HttpHeaders;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpMethod; import org.springframework.http.HttpMethod;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.http.HttpStatus;
import org.springframework.http.client.AbstractClientHttpResponse;
import org.springframework.web.client.ResponseErrorHandler;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
/** /**
* Test For {@link EnhancedRestTemplateReporter}. * Test for {@link EnhancedRestTemplateReporter}
* * @author lepdou 2022-09-06
* @author wh 2022/6/22
*/ */
@RunWith(SpringRunner.class) @RunWith(MockitoJUnitRunner.class)
@SpringBootTest(classes = EnhancedRestTemplateReporterTest.TestApplication.class,
properties = {"spring.cloud.polaris.namespace=Test", "spring.cloud.polaris.service=TestApp"})
public class EnhancedRestTemplateReporterTest { public class EnhancedRestTemplateReporterTest {
private static MockedStatic<MetadataContextHolder> mockedMetadataContextHolder;
private static MockedStatic<ApplicationContextAwareUtils> mockedApplicationContextAwareUtils;
@Mock
private ConsumerAPI consumerAPI;
@Mock
private RpcEnhancementReporterProperties reporterProperties;
@Mock
private ResponseErrorHandler delegate;
@InjectMocks
private EnhancedRestTemplateReporter enhancedRestTemplateReporter;
@BeforeClass
public static void beforeClass() {
mockedApplicationContextAwareUtils = Mockito.mockStatic(ApplicationContextAwareUtils.class);
mockedApplicationContextAwareUtils.when(() -> ApplicationContextAwareUtils.getProperties(anyString()))
.thenReturn("caller");
MetadataContext metadataContext = Mockito.mock(MetadataContext.class);
// mock transitive metadata
Map<String, String> loadBalancerContext = new HashMap<>();
loadBalancerContext.put("host", "1.1.1.1");
loadBalancerContext.put("port", "8080");
when(metadataContext.getFragmentContext(MetadataContext.FRAGMENT_LOAD_BALANCER)).thenReturn(loadBalancerContext);
mockedMetadataContextHolder = Mockito.mockStatic(MetadataContextHolder.class);
mockedMetadataContextHolder.when(MetadataContextHolder::get).thenReturn(metadataContext);
}
@AfterClass
public static void afterClass() {
mockedApplicationContextAwareUtils.close();
mockedMetadataContextHolder.close();
}
@Before
public void before() {
enhancedRestTemplateReporter.setDelegateHandler(delegate);
}
@Test @Test
public void handleError() throws Exception { public void testHasError() throws IOException {
ConsumerAPI consumerAPI = mock(ConsumerAPI.class); when(delegate.hasError(any())).thenReturn(true);
EnhancedRestTemplateReporter enhancedRestTemplateReporter =
new EnhancedRestTemplateReporter(mock(RpcEnhancementReporterProperties.class), consumerAPI, null); MockedClientHttpResponse response = new MockedClientHttpResponse();
Assert.assertTrue(enhancedRestTemplateReporter.hasError(response));
String realHasError = response.getHeaders().getFirst(EnhancedRestTemplateReporter.HEADER_HAS_ERROR);
Assert.assertEquals("true", realHasError);
}
@Test
public void testHandleHasError() throws IOException {
when(reporterProperties.isEnabled()).thenReturn(true);
when(delegate.hasError(any())).thenReturn(true);
MockedClientHttpResponse response = new MockedClientHttpResponse();
enhancedRestTemplateReporter.hasError(response);
URI uri = mock(URI.class); URI uri = mock(URI.class);
when(uri.getPath()).thenReturn("/test"); enhancedRestTemplateReporter.handleError(uri, HttpMethod.GET, response);
when(uri.getHost()).thenReturn("host");
HttpURLConnection httpURLConnection = mock(HttpURLConnection.class); verify(consumerAPI).updateServiceCallResult(any());
URL url = mock(URL.class); verify(delegate).handleError(uri, HttpMethod.GET, response);
when(httpURLConnection.getURL()).thenReturn(url);
when(url.getHost()).thenReturn("127.0.0.1");
when(url.getPort()).thenReturn(8080);
when(httpURLConnection.getResponseCode()).thenReturn(200);
SimpleClientHttpResponseTest clientHttpResponse = new SimpleClientHttpResponseTest(httpURLConnection);
enhancedRestTemplateReporter.handleError(uri, HttpMethod.GET, clientHttpResponse);
when(consumerAPI.unWatchService(null)).thenReturn(true);
} }
@SpringBootApplication @Test
protected static class TestApplication { public void testHandleHasNotError() throws IOException {
when(reporterProperties.isEnabled()).thenReturn(true);
when(delegate.hasError(any())).thenReturn(false);
MockedClientHttpResponse response = new MockedClientHttpResponse();
enhancedRestTemplateReporter.hasError(response);
URI uri = mock(URI.class);
enhancedRestTemplateReporter.handleError(uri, HttpMethod.GET, response);
verify(consumerAPI).updateServiceCallResult(any());
verify(delegate, times(0)).handleError(uri, HttpMethod.GET, response);
}
@Test
public void testReportSwitchOff() throws IOException {
when(reporterProperties.isEnabled()).thenReturn(false);
when(delegate.hasError(any())).thenReturn(true);
MockedClientHttpResponse response = new MockedClientHttpResponse();
enhancedRestTemplateReporter.hasError(response);
URI uri = mock(URI.class);
enhancedRestTemplateReporter.handleError(uri, HttpMethod.GET, response);
verify(consumerAPI, times(0)).updateServiceCallResult(any());
verify(delegate).handleError(uri, HttpMethod.GET, response);
}
class MockedClientHttpResponse extends AbstractClientHttpResponse {
private HttpHeaders headers;
MockedClientHttpResponse() {
this.headers = new HttpHeaders();
}
@Override
public int getRawStatusCode() throws IOException {
return 0;
}
@Override
public String getStatusText() throws IOException {
return null;
}
@Override
public void close() {
}
@Override
public InputStream getBody() throws IOException {
return null;
}
@Override
public HttpHeaders getHeaders() {
return headers;
}
@Override
public HttpStatus getStatusCode() throws IOException {
return HttpStatus.OK;
}
} }
} }

@ -1,105 +0,0 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.tencent.cloud.rpc.enhancement.resttemplate;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import org.springframework.http.HttpHeaders;
import org.springframework.http.client.AbstractClientHttpResponse;
import org.springframework.lang.Nullable;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* Mock Test for {@link AbstractClientHttpResponse}.
*
* @author wh 2022/6/22
*/
public class SimpleClientHttpResponseTest extends AbstractClientHttpResponse {
private final HttpURLConnection connection;
@Nullable
private HttpHeaders headers;
@Nullable
private InputStream responseStream;
SimpleClientHttpResponseTest(HttpURLConnection connection) {
this.connection = connection;
}
@Override
public int getRawStatusCode() throws IOException {
return this.connection.getResponseCode();
}
@Override
public String getStatusText() throws IOException {
String result = this.connection.getResponseMessage();
return (result != null) ? result : "";
}
@Override
public HttpHeaders getHeaders() {
if (this.headers == null) {
this.headers = new HttpHeaders();
// Header field 0 is the status line for most HttpURLConnections, but not on GAE
String name = this.connection.getHeaderFieldKey(0);
if (StringUtils.hasLength(name)) {
this.headers.add(name, this.connection.getHeaderField(0));
}
int i = 1;
while (true) {
name = this.connection.getHeaderFieldKey(i);
if (!StringUtils.hasLength(name)) {
break;
}
this.headers.add(name, this.connection.getHeaderField(i));
i++;
}
}
return this.headers;
}
@Override
public InputStream getBody() throws IOException {
InputStream errorStream = this.connection.getErrorStream();
this.responseStream = (errorStream != null ? errorStream : this.connection.getInputStream());
return this.responseStream;
}
@Override
public void close() {
try {
if (this.responseStream == null) {
getBody();
}
StreamUtils.drain(this.responseStream);
this.responseStream.close();
}
catch (Exception ex) {
// ignore
}
}
}
Loading…
Cancel
Save