From 0dd3cadc103c83e67b7d4d10e426a95fbfd6d4cc Mon Sep 17 00:00:00 2001 From: lepdou Date: Mon, 19 Sep 2022 14:52:44 +0800 Subject: [PATCH] remove useless code for rest template router (#601) --- CHANGELOG.md | 1 + ...dBalancerInterceptorBeanPostProcessor.java | 65 ----- .../config/RouterAutoConfiguration.java | 8 - .../PolarisLoadBalancerInterceptor.java | 154 ------------ ...ancerInterceptorBeanPostProcessorTest.java | 94 ------- .../PolarisLoadBalancerInterceptorTest.java | 231 ------------------ ...outerLabelRestTemplateInterceptorTest.java | 1 - 7 files changed, 1 insertion(+), 553 deletions(-) delete mode 100644 spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/beanprocessor/LoadBalancerInterceptorBeanPostProcessor.java delete mode 100644 spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/resttemplate/PolarisLoadBalancerInterceptor.java delete mode 100644 spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/beanprocessor/LoadBalancerInterceptorBeanPostProcessorTest.java delete mode 100644 spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/resttemplate/PolarisLoadBalancerInterceptorTest.java diff --git a/CHANGELOG.md b/CHANGELOG.md index 3943c4a1..8521a532 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,3 +3,4 @@ - [Fix issue 593:When the project depends on spring-retry, executing restTemplate to call microservice and reporting NPE error](https://github.com/Tencent/spring-cloud-tencent/pull/594) - [Optimize: remove discovery module useless code](https://github.com/Tencent/spring-cloud-tencent/pull/595) +- [Optimize: remove useless code for rest template router](https://github.com/Tencent/spring-cloud-tencent/pull/601) diff --git a/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/beanprocessor/LoadBalancerInterceptorBeanPostProcessor.java b/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/beanprocessor/LoadBalancerInterceptorBeanPostProcessor.java deleted file mode 100644 index fcca546d..00000000 --- a/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/beanprocessor/LoadBalancerInterceptorBeanPostProcessor.java +++ /dev/null @@ -1,65 +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.polaris.router.beanprocessor; - -import java.util.List; - -import com.tencent.cloud.common.metadata.StaticMetadataManager; -import com.tencent.cloud.common.util.BeanFactoryUtils; -import com.tencent.cloud.polaris.router.RouterRuleLabelResolver; -import com.tencent.cloud.polaris.router.resttemplate.PolarisLoadBalancerInterceptor; -import com.tencent.cloud.polaris.router.spi.SpringWebRouterLabelResolver; - -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.BeanFactory; -import org.springframework.beans.factory.BeanFactoryAware; -import org.springframework.beans.factory.config.BeanPostProcessor; -import org.springframework.cloud.client.loadbalancer.LoadBalancerClient; -import org.springframework.cloud.client.loadbalancer.LoadBalancerInterceptor; -import org.springframework.cloud.client.loadbalancer.LoadBalancerRequestFactory; - -/** - * Replace LoadBalancerInterceptor with PolarisLoadBalancerInterceptor. - * PolarisLoadBalancerInterceptor can pass routing context information. - * - *@author lepdou 2022-05-18 - */ -public class LoadBalancerInterceptorBeanPostProcessor implements BeanPostProcessor, BeanFactoryAware { - - private BeanFactory factory; - - @Override - public void setBeanFactory(BeanFactory beanFactory) throws BeansException { - this.factory = beanFactory; - } - - @Override - public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { - if (bean instanceof LoadBalancerInterceptor) { - LoadBalancerRequestFactory requestFactory = this.factory.getBean(LoadBalancerRequestFactory.class); - LoadBalancerClient loadBalancerClient = this.factory.getBean(LoadBalancerClient.class); - List routerLabelResolvers = BeanFactoryUtils.getBeans(factory, SpringWebRouterLabelResolver.class); - StaticMetadataManager staticMetadataManager = this.factory.getBean(StaticMetadataManager.class); - RouterRuleLabelResolver routerRuleLabelResolver = this.factory.getBean(RouterRuleLabelResolver.class); - - return new PolarisLoadBalancerInterceptor(loadBalancerClient, requestFactory, - routerLabelResolvers, staticMetadataManager, routerRuleLabelResolver); - } - return bean; - } -} diff --git a/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/config/RouterAutoConfiguration.java b/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/config/RouterAutoConfiguration.java index 4b60b75b..f9e03117 100644 --- a/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/config/RouterAutoConfiguration.java +++ b/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/config/RouterAutoConfiguration.java @@ -25,7 +25,6 @@ import java.util.List; import com.tencent.cloud.common.metadata.StaticMetadataManager; import com.tencent.cloud.polaris.context.ServiceRuleManager; import com.tencent.cloud.polaris.router.RouterRuleLabelResolver; -import com.tencent.cloud.polaris.router.beanprocessor.LoadBalancerInterceptorBeanPostProcessor; import com.tencent.cloud.polaris.router.beanprocessor.ReactiveLoadBalancerClientFilterBeanPostProcessor; import com.tencent.cloud.polaris.router.config.properties.PolarisMetadataRouterProperties; import com.tencent.cloud.polaris.router.config.properties.PolarisNearByRouterProperties; @@ -60,13 +59,6 @@ import static org.springframework.core.Ordered.HIGHEST_PRECEDENCE; @Import({PolarisNearByRouterProperties.class, PolarisMetadataRouterProperties.class, PolarisRuleBasedRouterProperties.class}) public class RouterAutoConfiguration { - @Bean - @Order(HIGHEST_PRECEDENCE) - @ConditionalOnClass(name = "org.springframework.cloud.client.loadbalancer.LoadBalancerInterceptor") - public LoadBalancerInterceptorBeanPostProcessor loadBalancerInterceptorBeanPostProcessor() { - return new LoadBalancerInterceptorBeanPostProcessor(); - } - @Bean @Order(HIGHEST_PRECEDENCE) @ConditionalOnClass(name = "org.springframework.cloud.gateway.filter.ReactiveLoadBalancerClientFilter") diff --git a/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/resttemplate/PolarisLoadBalancerInterceptor.java b/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/resttemplate/PolarisLoadBalancerInterceptor.java deleted file mode 100644 index 8cd4c914..00000000 --- a/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/resttemplate/PolarisLoadBalancerInterceptor.java +++ /dev/null @@ -1,154 +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.polaris.router.resttemplate; - -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.net.URLEncoder; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.tencent.cloud.common.constant.RouterConstants; -import com.tencent.cloud.common.metadata.MetadataContext; -import com.tencent.cloud.common.metadata.MetadataContextHolder; -import com.tencent.cloud.common.metadata.StaticMetadataManager; -import com.tencent.cloud.common.util.JacksonUtils; -import com.tencent.cloud.common.util.expresstion.SpringWebExpressionLabelUtils; -import com.tencent.cloud.polaris.router.RouterRuleLabelResolver; -import com.tencent.cloud.polaris.router.spi.SpringWebRouterLabelResolver; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.springframework.cloud.client.loadbalancer.LoadBalancerClient; -import org.springframework.cloud.client.loadbalancer.LoadBalancerInterceptor; -import org.springframework.cloud.client.loadbalancer.LoadBalancerRequestFactory; -import org.springframework.core.Ordered; -import org.springframework.http.HttpRequest; -import org.springframework.http.client.ClientHttpRequestExecution; -import org.springframework.http.client.ClientHttpResponse; -import org.springframework.util.Assert; -import org.springframework.util.CollectionUtils; - -import static com.tencent.cloud.common.constant.ContextConstant.UTF_8; - -/** - * PolarisLoadBalancerInterceptor extends LoadBalancerInterceptor capabilities. - * Parses the label from the request and puts it into the RouterContext for routing. - * - * @author lepdou, cheese8 - */ -public class PolarisLoadBalancerInterceptor extends LoadBalancerInterceptor { - private static final Logger LOGGER = LoggerFactory.getLogger(PolarisLoadBalancerInterceptor.class); - - private final LoadBalancerClient loadBalancer; - private final LoadBalancerRequestFactory requestFactory; - private final List routerLabelResolvers; - private final StaticMetadataManager staticMetadataManager; - private final RouterRuleLabelResolver routerRuleLabelResolver; - - public PolarisLoadBalancerInterceptor(LoadBalancerClient loadBalancer, - LoadBalancerRequestFactory requestFactory, - List routerLabelResolvers, - StaticMetadataManager staticMetadataManager, - RouterRuleLabelResolver routerRuleLabelResolver) { - super(loadBalancer, requestFactory); - this.loadBalancer = loadBalancer; - this.requestFactory = requestFactory; - this.staticMetadataManager = staticMetadataManager; - this.routerRuleLabelResolver = routerRuleLabelResolver; - - if (!CollectionUtils.isEmpty(routerLabelResolvers)) { - routerLabelResolvers.sort(Comparator.comparingInt(Ordered::getOrder)); - this.routerLabelResolvers = routerLabelResolvers; - } - else { - this.routerLabelResolvers = null; - } - } - - @Override - public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { - final URI originalUri = request.getURI(); - String peerServiceName = originalUri.getHost(); - Assert.state(peerServiceName != null, - "Request URI does not contain a valid hostname: " + originalUri); - - setLabelsToHeaders(request, body, peerServiceName); - - return this.loadBalancer.execute(peerServiceName, - new PolarisLoadBalancerRequest<>(request, this.requestFactory.createRequest(request, body, execution))); - } - - void setLabelsToHeaders(HttpRequest request, byte[] body, String peerServiceName) { - // local service labels - Map labels = new HashMap<>(staticMetadataManager.getMergedStaticMetadata()); - - // labels from rule expression - Set expressionLabelKeys = routerRuleLabelResolver.getExpressionLabelKeys(MetadataContext.LOCAL_NAMESPACE, - MetadataContext.LOCAL_SERVICE, peerServiceName); - - Map ruleExpressionLabels = getExpressionLabels(request, expressionLabelKeys); - if (!CollectionUtils.isEmpty(ruleExpressionLabels)) { - labels.putAll(ruleExpressionLabels); - } - - // labels from request - if (!CollectionUtils.isEmpty(routerLabelResolvers)) { - routerLabelResolvers.forEach(resolver -> { - try { - Map customResolvedLabels = resolver.resolve(request, body, expressionLabelKeys); - if (!CollectionUtils.isEmpty(customResolvedLabels)) { - labels.putAll(customResolvedLabels); - } - } - catch (Throwable t) { - LOGGER.error("[SCT][Router] revoke RouterLabelResolver occur some exception. ", t); - } - }); - } - - // labels from downstream - Map transitiveLabels = MetadataContextHolder.get() - .getFragmentContext(MetadataContext.FRAGMENT_TRANSITIVE); - labels.putAll(transitiveLabels); - - // pass label by header - String encodedLabelsContent; - try { - encodedLabelsContent = URLEncoder.encode(JacksonUtils.serialize2Json(labels), UTF_8); - } - catch (UnsupportedEncodingException e) { - throw new RuntimeException("unsupported charset exception " + UTF_8); - } - request.getHeaders().set(RouterConstants.ROUTER_LABEL_HEADER, encodedLabelsContent); - } - - private Map getExpressionLabels(HttpRequest request, Set labelKeys) { - if (CollectionUtils.isEmpty(labelKeys)) { - return Collections.emptyMap(); - } - - return SpringWebExpressionLabelUtils.resolve(request, labelKeys); - } -} diff --git a/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/beanprocessor/LoadBalancerInterceptorBeanPostProcessorTest.java b/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/beanprocessor/LoadBalancerInterceptorBeanPostProcessorTest.java deleted file mode 100644 index 057759af..00000000 --- a/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/beanprocessor/LoadBalancerInterceptorBeanPostProcessorTest.java +++ /dev/null @@ -1,94 +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.polaris.router.beanprocessor; - -import com.tencent.cloud.common.metadata.StaticMetadataManager; -import com.tencent.cloud.common.util.BeanFactoryUtils; -import com.tencent.cloud.polaris.router.RouterRuleLabelResolver; -import com.tencent.cloud.polaris.router.resttemplate.PolarisLoadBalancerInterceptor; -import com.tencent.cloud.polaris.router.spi.SpringWebRouterLabelResolver; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.MockedStatic; -import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; - -import org.springframework.beans.factory.BeanFactory; -import org.springframework.cloud.client.loadbalancer.LoadBalancerClient; -import org.springframework.cloud.client.loadbalancer.LoadBalancerInterceptor; -import org.springframework.cloud.client.loadbalancer.LoadBalancerRequestFactory; - -import static org.mockito.Mockito.when; - -/** - * Test for ${@link LoadBalancerInterceptorBeanPostProcessor}. - * - * @author lepdou 2022-05-26 - */ -@RunWith(MockitoJUnitRunner.class) -public class LoadBalancerInterceptorBeanPostProcessorTest { - - @Mock - private LoadBalancerClient loadBalancerClient; - @Mock - private LoadBalancerRequestFactory loadBalancerRequestFactory; - @Mock - private StaticMetadataManager staticMetadataManager; - @Mock - private RouterRuleLabelResolver routerRuleLabelResolver; - @Mock - private BeanFactory beanFactory; - - @Test - public void testWrapperLoadBalancerInterceptor() { - when(beanFactory.getBean(LoadBalancerRequestFactory.class)).thenReturn(loadBalancerRequestFactory); - when(beanFactory.getBean(LoadBalancerClient.class)).thenReturn(loadBalancerClient); - when(beanFactory.getBean(StaticMetadataManager.class)).thenReturn(staticMetadataManager); - when(beanFactory.getBean(RouterRuleLabelResolver.class)).thenReturn(routerRuleLabelResolver); - - try (MockedStatic mockedBeanFactoryUtils = Mockito.mockStatic(BeanFactoryUtils.class)) { - mockedBeanFactoryUtils.when(() -> BeanFactoryUtils.getBeans(beanFactory, SpringWebRouterLabelResolver.class)) - .thenReturn(null); - LoadBalancerInterceptor loadBalancerInterceptor = new LoadBalancerInterceptor(loadBalancerClient, loadBalancerRequestFactory); - - LoadBalancerInterceptorBeanPostProcessor processor = new LoadBalancerInterceptorBeanPostProcessor(); - processor.setBeanFactory(beanFactory); - - Object bean = processor.postProcessBeforeInitialization(loadBalancerInterceptor, ""); - - Assert.assertTrue(bean instanceof PolarisLoadBalancerInterceptor); - } - } - - @Test - public void testNotWrapperLoadBalancerInterceptor() { - LoadBalancerInterceptorBeanPostProcessor processor = new LoadBalancerInterceptorBeanPostProcessor(); - processor.setBeanFactory(beanFactory); - - OtherBean otherBean = new OtherBean(); - Object bean = processor.postProcessBeforeInitialization(otherBean, ""); - Assert.assertFalse(bean instanceof PolarisLoadBalancerInterceptor); - Assert.assertTrue(bean instanceof OtherBean); - } - - static class OtherBean { - - } -} diff --git a/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/resttemplate/PolarisLoadBalancerInterceptorTest.java b/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/resttemplate/PolarisLoadBalancerInterceptorTest.java deleted file mode 100644 index c3e5372d..00000000 --- a/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/resttemplate/PolarisLoadBalancerInterceptorTest.java +++ /dev/null @@ -1,231 +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.polaris.router.resttemplate; - - -import java.net.URI; -import java.net.URLDecoder; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import com.tencent.cloud.common.constant.RouterConstants; -import com.tencent.cloud.common.metadata.MetadataContext; -import com.tencent.cloud.common.metadata.MetadataContextHolder; -import com.tencent.cloud.common.metadata.StaticMetadataManager; -import com.tencent.cloud.common.util.ApplicationContextAwareUtils; -import com.tencent.cloud.common.util.JacksonUtils; -import com.tencent.cloud.polaris.router.RouterRuleLabelResolver; -import com.tencent.cloud.polaris.router.spi.SpringWebRouterLabelResolver; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.MockedStatic; -import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; - -import org.springframework.cloud.client.ServiceInstance; -import org.springframework.cloud.client.loadbalancer.LoadBalancerClient; -import org.springframework.cloud.client.loadbalancer.LoadBalancerRequest; -import org.springframework.cloud.client.loadbalancer.LoadBalancerRequestFactory; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpRequest; -import org.springframework.http.client.ClientHttpResponse; - -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -/** - * test for {@link PolarisLoadBalancerInterceptor} - * @author lepdou 2022-05-26 - */ -@RunWith(MockitoJUnitRunner.class) -public class PolarisLoadBalancerInterceptorTest { - - private static MockedStatic mockedApplicationContextAwareUtils; - private static MockedStatic mockedMetadataContextHolder; - @Mock - private LoadBalancerClient loadBalancerClient; - @Mock - private LoadBalancerRequestFactory loadBalancerRequestFactory; - @Mock - private SpringWebRouterLabelResolver routerLabelResolver; - @Mock - private StaticMetadataManager staticMetadataManager; - @Mock - private RouterRuleLabelResolver routerRuleLabelResolver; - - @BeforeClass - public static void beforeClass() { - mockedApplicationContextAwareUtils = Mockito.mockStatic(ApplicationContextAwareUtils.class); - mockedApplicationContextAwareUtils.when(() -> ApplicationContextAwareUtils.getProperties(anyString())) - .thenReturn("callerService"); - - mockedMetadataContextHolder = Mockito.mockStatic(MetadataContextHolder.class); - } - - @AfterClass - public static void afterClass() { - mockedApplicationContextAwareUtils.close(); - mockedMetadataContextHolder.close(); - } - - @Test - public void testProxyRibbonLoadBalance() throws Exception { - String callerService = "callerService"; - String calleeService = "calleeService"; - HttpRequest request = new MockedHttpRequest("http://" + calleeService + "/user/get"); - - // mock local metadata - Map localMetadata = new HashMap<>(); - localMetadata.put("k1", "v1"); - localMetadata.put("k2", "v2"); - when(staticMetadataManager.getMergedStaticMetadata()).thenReturn(localMetadata); - - // mock expression rule labels - - Set expressionKeys = new HashSet<>(); - expressionKeys.add("${http.method}"); - expressionKeys.add("${http.uri}"); - when(routerRuleLabelResolver.getExpressionLabelKeys(callerService, callerService, calleeService)).thenReturn(expressionKeys); - - // mock custom resolved from request - Map customResolvedLabels = new HashMap<>(); - customResolvedLabels.put("k3", "v3"); - customResolvedLabels.put("k4", "v4"); - when(routerLabelResolver.resolve(request, null, expressionKeys)).thenReturn(customResolvedLabels); - - MetadataContext metadataContext = Mockito.mock(MetadataContext.class); - - // mock transitive metadata - Map transitiveLabels = new HashMap<>(); - transitiveLabels.put("k1", "v1"); - transitiveLabels.put("k2", "v22"); - when(metadataContext.getFragmentContext(MetadataContext.FRAGMENT_TRANSITIVE)).thenReturn(transitiveLabels); - - mockedMetadataContextHolder.when(MetadataContextHolder::get).thenReturn(metadataContext); - - LoadBalancerRequest loadBalancerRequest = new MockedLoadBalancerRequest<>(); - when(loadBalancerRequestFactory.createRequest(request, null, null)).thenReturn(loadBalancerRequest); - - PolarisLoadBalancerInterceptor polarisLoadBalancerInterceptor = new PolarisLoadBalancerInterceptor(loadBalancerClient, - loadBalancerRequestFactory, Collections.singletonList(routerLabelResolver), staticMetadataManager, routerRuleLabelResolver); - - polarisLoadBalancerInterceptor.intercept(request, null, null); - - verify(staticMetadataManager).getMergedStaticMetadata(); - verify(routerRuleLabelResolver).getExpressionLabelKeys(callerService, callerService, calleeService); - verify(routerLabelResolver).resolve(request, null, expressionKeys); - } - - @Test - public void testRouterContext() throws Exception { - String callerService = "callerService"; - String calleeService = "calleeService"; - HttpRequest request = new MockedHttpRequest("http://" + calleeService + "/user/get"); - - // mock local metadata - Map localMetadata = new HashMap<>(); - localMetadata.put("k1", "v1"); - localMetadata.put("k2", "v2"); - when(staticMetadataManager.getMergedStaticMetadata()).thenReturn(localMetadata); - - // mock expression rule labels - - Set expressionKeys = new HashSet<>(); - expressionKeys.add("${http.method}"); - expressionKeys.add("${http.uri}"); - when(routerRuleLabelResolver.getExpressionLabelKeys(callerService, callerService, calleeService)).thenReturn(expressionKeys); - - // mock custom resolved from request - Map customResolvedLabels = new HashMap<>(); - customResolvedLabels.put("k2", "v22"); - customResolvedLabels.put("k4", "v4"); - when(routerLabelResolver.resolve(request, null, expressionKeys)).thenReturn(customResolvedLabels); - - MetadataContext metadataContext = Mockito.mock(MetadataContext.class); - - // mock transitive metadata - Map transitiveLabels = new HashMap<>(); - transitiveLabels.put("k1", "v1"); - transitiveLabels.put("k2", "v22"); - when(metadataContext.getFragmentContext(MetadataContext.FRAGMENT_TRANSITIVE)).thenReturn(transitiveLabels); - - mockedMetadataContextHolder.when(MetadataContextHolder::get).thenReturn(metadataContext); - - PolarisLoadBalancerInterceptor polarisLoadBalancerInterceptor = new PolarisLoadBalancerInterceptor(loadBalancerClient, - loadBalancerRequestFactory, Collections.singletonList(routerLabelResolver), staticMetadataManager, routerRuleLabelResolver); - - polarisLoadBalancerInterceptor.setLabelsToHeaders(request, null, calleeService); - - verify(staticMetadataManager).getMergedStaticMetadata(); - verify(routerRuleLabelResolver).getExpressionLabelKeys(callerService, callerService, calleeService); - verify(routerLabelResolver).resolve(request, null, expressionKeys); - - - Map headers = JacksonUtils.deserialize2Map(URLDecoder.decode(request.getHeaders() - .get(RouterConstants.ROUTER_LABEL_HEADER).get(0), "UTF-8")); - Assert.assertEquals("v1", headers.get("k1")); - Assert.assertEquals("v22", headers.get("k2")); - Assert.assertEquals("v4", headers.get("k4")); - Assert.assertEquals("GET", headers.get("${http.method}")); - Assert.assertEquals("/user/get", headers.get("${http.uri}")); - } - - static class MockedLoadBalancerRequest implements LoadBalancerRequest { - - @Override - public T apply(ServiceInstance instance) throws Exception { - return null; - } - } - - static class MockedHttpRequest implements HttpRequest { - - private URI uri; - - private HttpHeaders httpHeaders = new HttpHeaders(); - - MockedHttpRequest(String url) { - this.uri = URI.create(url); - } - - @Override - public String getMethodValue() { - return HttpMethod.GET.name(); - } - - @Override - public URI getURI() { - return uri; - } - - @Override - public HttpHeaders getHeaders() { - return httpHeaders; - } - } -} diff --git a/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/resttemplate/RouterLabelRestTemplateInterceptorTest.java b/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/resttemplate/RouterLabelRestTemplateInterceptorTest.java index 95f08565..b745c877 100644 --- a/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/resttemplate/RouterLabelRestTemplateInterceptorTest.java +++ b/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/resttemplate/RouterLabelRestTemplateInterceptorTest.java @@ -37,7 +37,6 @@ import com.tencent.cloud.polaris.router.RouterRuleLabelResolver; import com.tencent.cloud.polaris.router.spi.SpringWebRouterLabelResolver; import org.assertj.core.api.Assertions; import org.junit.AfterClass; -import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith;