feature: add polaris ring hash load balancer (#971)

pull/991/head
Shanyou Yu (Sean Yu) 2 years ago committed by GitHub
parent ed6596ab5b
commit 89536c5c96
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -8,3 +8,4 @@
- [feature: add config for customized local port.](https://github.com/Tencent/spring-cloud-tencent/pull/957) - [feature: add config for customized local port.](https://github.com/Tencent/spring-cloud-tencent/pull/957)
- [refactor:refactor reactor code in router module.](https://github.com/Tencent/spring-cloud-tencent/pull/959) - [refactor:refactor reactor code in router module.](https://github.com/Tencent/spring-cloud-tencent/pull/959)
- [refactor: refactor circuitbreaker .](https://github.com/Tencent/spring-cloud-tencent/pull/964) - [refactor: refactor circuitbreaker .](https://github.com/Tencent/spring-cloud-tencent/pull/964)
- [feature: add polaris ring hash load balancer .](https://github.com/Tencent/spring-cloud-tencent/pull/971)

@ -29,7 +29,9 @@ import org.springframework.cloud.client.ConditionalOnReactiveDiscoveryEnabled;
import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.discovery.ReactiveDiscoveryClient; import org.springframework.cloud.client.discovery.ReactiveDiscoveryClient;
import org.springframework.cloud.loadbalancer.core.RandomLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ReactorLoadBalancer; import org.springframework.cloud.loadbalancer.core.ReactorLoadBalancer;
import org.springframework.cloud.loadbalancer.core.RoundRobinLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier; import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory; import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.ConfigurableApplicationContext;
@ -53,15 +55,43 @@ public class PolarisLoadBalancerClientConfiguration {
*/ */
private static final int REACTIVE_SERVICE_INSTANCE_SUPPLIER_ORDER = 193827465; private static final int REACTIVE_SERVICE_INSTANCE_SUPPLIER_ORDER = 193827465;
private final static String STRATEGY_WEIGHT = "polarisWeighted"; @Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(value = "spring.cloud.polaris.loadbalancer.strategy", havingValue = "roundRobin", matchIfMissing = true)
public ReactorLoadBalancer<ServiceInstance> roundRobinLoadBalancer(Environment environment,
LoadBalancerClientFactory loadBalancerClientFactory) {
String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);
return new RoundRobinLoadBalancer(
loadBalancerClientFactory.getLazyProvider(name, ServiceInstanceListSupplier.class), name);
}
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(value = "spring.cloud.polaris.loadbalancer.strategy", havingValue = "random")
public ReactorLoadBalancer<ServiceInstance> randomLoadBalancer(Environment environment,
LoadBalancerClientFactory loadBalancerClientFactory) {
String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);
return new RandomLoadBalancer(
loadBalancerClientFactory.getLazyProvider(name, ServiceInstanceListSupplier.class), name);
}
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(value = "spring.cloud.polaris.loadbalancer.strategy", havingValue = "polarisWeightedRandom")
public ReactorLoadBalancer<ServiceInstance> polarisWeightedLoadBalancer(Environment environment,
LoadBalancerClientFactory loadBalancerClientFactory, RouterAPI routerAPI) {
String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);
return new PolarisWeightedRandomLoadBalancer(name,
loadBalancerClientFactory.getLazyProvider(name, ServiceInstanceListSupplier.class), routerAPI);
}
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
@ConditionalOnProperty(value = "spring.cloud.polaris.loadbalancer.strategy", havingValue = STRATEGY_WEIGHT) @ConditionalOnProperty(value = "spring.cloud.polaris.loadbalancer.strategy", havingValue = "polarisRingHash")
public ReactorLoadBalancer<ServiceInstance> polarisLoadBalancer(Environment environment, public ReactorLoadBalancer<ServiceInstance> polarisRingHashLoadBalancer(Environment environment,
LoadBalancerClientFactory loadBalancerClientFactory, RouterAPI routerAPI) { LoadBalancerClientFactory loadBalancerClientFactory, RouterAPI routerAPI) {
String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME); String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);
return new PolarisLoadBalancer(name, return new PolarisRingHashLoadBalancer(name,
loadBalancerClientFactory.getLazyProvider(name, ServiceInstanceListSupplier.class), routerAPI); loadBalancerClientFactory.getLazyProvider(name, ServiceInstanceListSupplier.class), routerAPI);
} }

@ -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.polaris.loadbalancer;
import com.tencent.cloud.common.metadata.MetadataContextHolder;
/**
* PolarisLoadBalancerRingHashKeyProvider.
*
* @author seanthefish
*/
public final class PolarisLoadBalancerRingHashKeyProvider {
private static final String LOAD_BALANCER_HASH_KEY = "LOAD_BALANCER_HASH_KEY";
private PolarisLoadBalancerRingHashKeyProvider() {
}
public static void hashKey(String key) {
MetadataContextHolder.get().setLoadbalancer(LOAD_BALANCER_HASH_KEY, key);
}
static String getHashKey() {
return MetadataContextHolder.get().getLoadbalancerMetadata().get(LOAD_BALANCER_HASH_KEY);
}
}

@ -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.loadbalancer;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import com.tencent.cloud.common.metadata.MetadataContext;
import com.tencent.cloud.common.pojo.PolarisServiceInstance;
import com.tencent.polaris.api.config.consumer.LoadBalanceConfig;
import com.tencent.polaris.api.pojo.DefaultServiceInstances;
import com.tencent.polaris.api.pojo.Instance;
import com.tencent.polaris.api.pojo.ServiceInstances;
import com.tencent.polaris.api.pojo.ServiceKey;
import com.tencent.polaris.api.rpc.Criteria;
import com.tencent.polaris.router.api.core.RouterAPI;
import com.tencent.polaris.router.api.rpc.ProcessLoadBalanceRequest;
import com.tencent.polaris.router.api.rpc.ProcessLoadBalanceResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Mono;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.DefaultResponse;
import org.springframework.cloud.client.loadbalancer.EmptyResponse;
import org.springframework.cloud.client.loadbalancer.Request;
import org.springframework.cloud.client.loadbalancer.Response;
import org.springframework.cloud.loadbalancer.core.NoopServiceInstanceListSupplier;
import org.springframework.cloud.loadbalancer.core.ReactorServiceInstanceLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
/**
* PolarisRingHashLoadBalancer.
*
* @author sean yu
*/
public class PolarisRingHashLoadBalancer implements ReactorServiceInstanceLoadBalancer {
private static final Logger log = LoggerFactory.getLogger(PolarisWeightedRandomLoadBalancer.class);
private final String serviceId;
private final RouterAPI routerAPI;
private ObjectProvider<ServiceInstanceListSupplier> supplierObjectProvider;
public PolarisRingHashLoadBalancer(String serviceId,
ObjectProvider<ServiceInstanceListSupplier> supplierObjectProvider,
RouterAPI routerAPI) {
this.serviceId = serviceId;
this.supplierObjectProvider = supplierObjectProvider;
this.routerAPI = routerAPI;
}
private static ServiceInstances convertToPolarisServiceInstances(List<ServiceInstance> serviceInstances) {
ServiceKey serviceKey = new ServiceKey(MetadataContext.LOCAL_NAMESPACE, serviceInstances.get(0).getServiceId());
List<Instance> polarisInstances = serviceInstances.stream()
.map(serviceInstance -> ((PolarisServiceInstance) serviceInstance).getPolarisInstance())
.collect(Collectors.toList());
return new DefaultServiceInstances(serviceKey, polarisInstances);
}
@Override
public Mono<Response<ServiceInstance>> choose(Request request) {
ServiceInstanceListSupplier supplier = supplierObjectProvider
.getIfAvailable(NoopServiceInstanceListSupplier::new);
String hashKey = Optional.ofNullable(PolarisLoadBalancerRingHashKeyProvider.getHashKey()).orElse("");
return supplier.get(request).next().map(serviceInstances -> getInstanceResponse(serviceInstances, hashKey));
}
private Response<ServiceInstance> getInstanceResponse(List<ServiceInstance> serviceInstances, String hashKey) {
if (serviceInstances.isEmpty()) {
log.warn("No servers available for service: " + this.serviceId);
return new EmptyResponse();
}
ProcessLoadBalanceRequest request = new ProcessLoadBalanceRequest();
request.setDstInstances(convertToPolarisServiceInstances(serviceInstances));
request.setLbPolicy(LoadBalanceConfig.LOAD_BALANCE_RING_HASH);
Criteria criteria = new Criteria();
criteria.setHashKey(hashKey);
request.setCriteria(criteria);
try {
ProcessLoadBalanceResponse response = routerAPI.processLoadBalance(request);
return new DefaultResponse(new PolarisServiceInstance(response.getTargetInstance()));
}
catch (Exception e) {
log.warn("PolarisRoutingLoadbalancer error", e);
return new EmptyResponse();
}
}
}

@ -42,7 +42,7 @@ import org.springframework.cloud.client.loadbalancer.EmptyResponse;
import org.springframework.cloud.client.loadbalancer.Request; import org.springframework.cloud.client.loadbalancer.Request;
import org.springframework.cloud.client.loadbalancer.Response; import org.springframework.cloud.client.loadbalancer.Response;
import org.springframework.cloud.loadbalancer.core.NoopServiceInstanceListSupplier; import org.springframework.cloud.loadbalancer.core.NoopServiceInstanceListSupplier;
import org.springframework.cloud.loadbalancer.core.RoundRobinLoadBalancer; import org.springframework.cloud.loadbalancer.core.ReactorServiceInstanceLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier; import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
/** /**
@ -50,18 +50,17 @@ import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
* *
* @author <a href="mailto:liaochuntao@live.com">liaochuntao</a> * @author <a href="mailto:liaochuntao@live.com">liaochuntao</a>
*/ */
public class PolarisLoadBalancer extends RoundRobinLoadBalancer { public class PolarisWeightedRandomLoadBalancer implements ReactorServiceInstanceLoadBalancer {
private static final Logger LOGGER = LoggerFactory.getLogger(PolarisLoadBalancer.class); private static final Logger log = LoggerFactory.getLogger(PolarisWeightedRandomLoadBalancer.class);
private final String serviceId; private final String serviceId;
private final RouterAPI routerAPI; private final RouterAPI routerAPI;
private final ObjectProvider<ServiceInstanceListSupplier> supplierObjectProvider; private ObjectProvider<ServiceInstanceListSupplier> supplierObjectProvider;
public PolarisLoadBalancer(String serviceId, ObjectProvider<ServiceInstanceListSupplier> supplierObjectProvider, RouterAPI routerAPI) { public PolarisWeightedRandomLoadBalancer(String serviceId, ObjectProvider<ServiceInstanceListSupplier> supplierObjectProvider, RouterAPI routerAPI) {
super(supplierObjectProvider, serviceId);
this.serviceId = serviceId; this.serviceId = serviceId;
this.supplierObjectProvider = supplierObjectProvider; this.supplierObjectProvider = supplierObjectProvider;
this.routerAPI = routerAPI; this.routerAPI = routerAPI;
@ -84,7 +83,7 @@ public class PolarisLoadBalancer extends RoundRobinLoadBalancer {
private Response<ServiceInstance> getInstanceResponse(List<ServiceInstance> serviceInstances) { private Response<ServiceInstance> getInstanceResponse(List<ServiceInstance> serviceInstances) {
if (serviceInstances.isEmpty()) { if (serviceInstances.isEmpty()) {
LOGGER.warn("No servers available for service: " + this.serviceId); log.warn("No servers available for service: " + this.serviceId);
return new EmptyResponse(); return new EmptyResponse();
} }
@ -98,7 +97,7 @@ public class PolarisLoadBalancer extends RoundRobinLoadBalancer {
return new DefaultResponse(new PolarisServiceInstance(response.getTargetInstance())); return new DefaultResponse(new PolarisServiceInstance(response.getTargetInstance()));
} }
catch (Exception e) { catch (Exception e) {
LOGGER.warn("PolarisRoutingLoadbalancer error", e); log.warn("PolarisRoutingLoadbalancer error", e);
return new EmptyResponse(); return new EmptyResponse();
} }
} }

@ -75,8 +75,8 @@
{ {
"name": "spring.cloud.polaris.loadbalancer.strategy", "name": "spring.cloud.polaris.loadbalancer.strategy",
"type": "java.lang.String", "type": "java.lang.String",
"defaultValue": "random", "defaultValue": "roundRobin",
"description": "retry,best_available,availability_filtering,round_robin,weighted_response_time,zone_avoidance,random,consistent_hash,weighted_random." "description": "loadbalancer strategy."
}, },
{ {
"name": "spring.cloud.nacos.discovery.enabled", "name": "spring.cloud.nacos.discovery.enabled",
@ -122,5 +122,28 @@
"description": "the nacos authentication cluster-name.", "description": "the nacos authentication cluster-name.",
"sourceType": "com.tencent.cloud.polaris.extend.nacos.NacosContextProperties" "sourceType": "com.tencent.cloud.polaris.extend.nacos.NacosContextProperties"
} }
],
"hints" : [
{
"name": "spring.cloud.polaris.loadbalancer.strategy",
"values": [
{
"value": "roundRobin",
"description": "round robin load balancer."
},
{
"value": "random",
"description": "random load balancer."
},
{
"value": "polarisWeightedRandom",
"description": "polaris weighted random load balancer."
},
{
"value": "polarisRingHash",
"description": "polaris ring hash load balancer."
}
]
}
] ]
} }

@ -0,0 +1,129 @@
/*
* 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.loadbalancer;
import java.util.ArrayList;
import java.util.List;
import com.tencent.cloud.common.metadata.StaticMetadataManager;
import com.tencent.cloud.common.metadata.config.MetadataLocalProperties;
import com.tencent.cloud.common.pojo.PolarisServiceInstance;
import com.tencent.cloud.common.util.ApplicationContextAwareUtils;
import com.tencent.polaris.api.pojo.Instance;
import com.tencent.polaris.router.api.core.RouterAPI;
import com.tencent.polaris.router.api.rpc.ProcessLoadBalanceResponse;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.Request;
import org.springframework.cloud.client.loadbalancer.Response;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import org.springframework.context.ApplicationContext;
import static com.tencent.cloud.common.metadata.MetadataContext.LOCAL_NAMESPACE;
import static com.tencent.cloud.common.metadata.MetadataContext.LOCAL_SERVICE;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* PolarisRingHashLoadBalancerTest.
*
* @author sean yu
*/
@ExtendWith(MockitoExtension.class)
public class PolarisRingHashLoadBalancerTest {
private static MockedStatic<ApplicationContextAwareUtils> mockedApplicationContextAwareUtils;
private static Instance testInstance;
@Mock
private RouterAPI routerAPI;
@Mock
private ObjectProvider<ServiceInstanceListSupplier> supplierObjectProvider;
@BeforeAll
static void beforeAll() {
mockedApplicationContextAwareUtils = Mockito.mockStatic(ApplicationContextAwareUtils.class);
mockedApplicationContextAwareUtils.when(() -> ApplicationContextAwareUtils.getProperties(anyString()))
.thenReturn("unit-test");
ApplicationContext applicationContext = mock(ApplicationContext.class);
MetadataLocalProperties metadataLocalProperties = mock(MetadataLocalProperties.class);
StaticMetadataManager staticMetadataManager = mock(StaticMetadataManager.class);
doReturn(metadataLocalProperties).when(applicationContext).getBean(MetadataLocalProperties.class);
doReturn(staticMetadataManager).when(applicationContext).getBean(StaticMetadataManager.class);
mockedApplicationContextAwareUtils.when(ApplicationContextAwareUtils::getApplicationContext)
.thenReturn(applicationContext);
testInstance = Instance.createDefaultInstance("instance-id", LOCAL_NAMESPACE,
LOCAL_SERVICE, "host", 8090);
}
@AfterAll
static void afterAll() {
mockedApplicationContextAwareUtils.close();
}
@Test
public void chooseNormalLogicTest_thenReturnAvailablePolarisInstance() {
Request request = Mockito.mock(Request.class);
List<ServiceInstance> mockInstanceList = new ArrayList<>();
mockInstanceList.add(new PolarisServiceInstance(testInstance));
ServiceInstanceListSupplier serviceInstanceListSupplier = Mockito.mock(ServiceInstanceListSupplier.class);
when(serviceInstanceListSupplier.get(request)).thenReturn(Flux.just(mockInstanceList));
when(supplierObjectProvider.getIfAvailable(any())).thenReturn(serviceInstanceListSupplier);
ProcessLoadBalanceResponse mockLbRes = new ProcessLoadBalanceResponse(testInstance);
when(routerAPI.processLoadBalance(any())).thenReturn(mockLbRes);
// request construct and execute invoke
PolarisRingHashLoadBalancer polarisRingHashLoadBalancer = new PolarisRingHashLoadBalancer(LOCAL_SERVICE, supplierObjectProvider, routerAPI);
Mono<Response<ServiceInstance>> responseMono = polarisRingHashLoadBalancer.choose(request);
ServiceInstance serviceInstance = responseMono.block().getServer();
// verify method has invoked
verify(supplierObjectProvider).getIfAvailable(any());
//result assert
Assertions.assertThat(serviceInstance).isNotNull();
Assertions.assertThat(serviceInstance instanceof PolarisServiceInstance).isTrue();
PolarisServiceInstance polarisServiceInstance = (PolarisServiceInstance) serviceInstance;
Assertions.assertThat(polarisServiceInstance.getPolarisInstance().getId()).isEqualTo("instance-id");
Assertions.assertThat(polarisServiceInstance.getPolarisInstance().getNamespace()).isEqualTo(LOCAL_NAMESPACE);
Assertions.assertThat(polarisServiceInstance.getPolarisInstance().getService()).isEqualTo(LOCAL_SERVICE);
Assertions.assertThat(polarisServiceInstance.getPolarisInstance().getHost()).isEqualTo("host");
Assertions.assertThat(polarisServiceInstance.getPolarisInstance().getPort()).isEqualTo(8090);
}
}

@ -20,6 +20,8 @@ package com.tencent.cloud.polaris.loadbalancer;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration; import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import com.tencent.polaris.router.api.core.RouterAPI; import com.tencent.polaris.router.api.core.RouterAPI;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@ -39,13 +41,13 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy;
* *
* @author Haotian Zhang * @author Haotian Zhang
*/ */
public class PolarisLoadBalancerAutoConfigurationTest { @ExtendWith(MockitoExtension.class)
public class PolarisWeightedRandomLoadBalancerAutoConfigurationTest {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withPropertyValues("spring.application.name=" + SERVICE_PROVIDER) .withPropertyValues("spring.application.name=" + SERVICE_PROVIDER)
.withPropertyValues("server.port=" + PORT) .withPropertyValues("server.port=" + PORT)
.withPropertyValues("spring.cloud.polaris.address=grpc://127.0.0.1:10081") .withPropertyValues("spring.cloud.polaris.address=grpc://127.0.0.1:10081")
.withPropertyValues("spring.cloud.polaris.loadbalancer.strategy=polarisWeighted")
.withConfiguration(AutoConfigurations.of( .withConfiguration(AutoConfigurations.of(
PolarisRibbonTest.class, PolarisRibbonTest.class,
PolarisLoadBalancerAutoConfiguration.class, PolarisLoadBalancerAutoConfiguration.class,
@ -62,6 +64,40 @@ public class PolarisLoadBalancerAutoConfigurationTest {
}); });
} }
@Test
public void testRandomInitialization() {
this.contextRunner.withPropertyValues("spring.cloud.polaris.loadbalancer.strategy=random").run(context -> {
assertThat(context).hasSingleBean(RouterAPI.class);
assertThat(context).hasSingleBean(RestTemplate.class);
assertThatThrownBy(() -> {
context.getBean(RestTemplate.class).getForEntity("http://wrong.url", String.class);
}).isInstanceOf(Exception.class);
});
}
@Test
public void testPolarisWeightedInitialization() {
this.contextRunner.withPropertyValues("spring.cloud.polaris.loadbalancer.strategy=polarisWeightedRandom").run(context -> {
assertThat(context).hasSingleBean(RouterAPI.class);
assertThat(context).hasSingleBean(RestTemplate.class);
assertThatThrownBy(() -> {
context.getBean(RestTemplate.class).getForEntity("http://wrong.url", String.class);
}).isInstanceOf(Exception.class);
});
}
@Test
public void testPolarisRingHashInitialization() {
this.contextRunner
.withPropertyValues("spring.cloud.polaris.loadbalancer.strategy=polarisRingHash").run(context -> {
assertThat(context).hasSingleBean(RouterAPI.class);
assertThat(context).hasSingleBean(RestTemplate.class);
assertThatThrownBy(() -> {
context.getBean(RestTemplate.class).getForEntity("http://wrong.url", String.class);
}).isInstanceOf(Exception.class);
});
}
@Configuration @Configuration
@EnableAutoConfiguration @EnableAutoConfiguration
static class PolarisRibbonTest { static class PolarisRibbonTest {

@ -52,12 +52,12 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
/** /**
* Test for {@link PolarisLoadBalancer}. * Test for {@link PolarisWeightedRandomLoadBalancer}.
* *
* @author rod.xu * @author rod.xu
*/ */
@ExtendWith(MockitoExtension.class) @ExtendWith(MockitoExtension.class)
public class PolarisLoadBalancerTest { public class PolarisWeightedRandomLoadBalancerTest {
private static MockedStatic<ApplicationContextAwareUtils> mockedApplicationContextAwareUtils; private static MockedStatic<ApplicationContextAwareUtils> mockedApplicationContextAwareUtils;
private static Instance testInstance; private static Instance testInstance;
@ -97,8 +97,8 @@ public class PolarisLoadBalancerTest {
when(routerAPI.processLoadBalance(any())).thenReturn(mockLbRes); when(routerAPI.processLoadBalance(any())).thenReturn(mockLbRes);
// request construct and execute invoke // request construct and execute invoke
PolarisLoadBalancer polarisLoadBalancer = new PolarisLoadBalancer(LOCAL_SERVICE, supplierObjectProvider, routerAPI); PolarisWeightedRandomLoadBalancer polarisWeightedRandomLoadBalancer = new PolarisWeightedRandomLoadBalancer(LOCAL_SERVICE, supplierObjectProvider, routerAPI);
Mono<Response<ServiceInstance>> responseMono = polarisLoadBalancer.choose(request); Mono<Response<ServiceInstance>> responseMono = polarisWeightedRandomLoadBalancer.choose(request);
ServiceInstance serviceInstance = responseMono.block().getServer(); ServiceInstance serviceInstance = responseMono.block().getServer();
// verify method has invoked // verify method has invoked
Loading…
Cancel
Save