Conflicts: CHANGELOG.mdpull/197/head
commit
f045b4cd4e
@ -1,3 +1,8 @@
|
||||
# Change Log
|
||||
---
|
||||
|
||||
|
||||
- [Feature: Support parse ratelimit rule expression labels.](https://github.com/Tencent/spring-cloud-tencent/pull/183)
|
||||
- [Feature: Router support request label.](https://github.com/Tencent/spring-cloud-tencent/pull/165)
|
||||
- [Feature: Support router expression label](https://github.com/Tencent/spring-cloud-tencent/pull/190)
|
||||
- [Add metadata transfer example.](https://github.com/Tencent/spring-cloud-tencent/pull/184)
|
||||
|
@ -0,0 +1,72 @@
|
||||
/*
|
||||
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
|
||||
*
|
||||
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
|
||||
*
|
||||
* Licensed under the BSD 3-Clause License (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://opensource.org/licenses/BSD-3-Clause
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software distributed
|
||||
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
|
||||
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations under the License.
|
||||
*
|
||||
*/
|
||||
|
||||
package com.tencent.cloud.polaris.ratelimit;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import com.tencent.cloud.common.util.ExpressionLabelUtils;
|
||||
import com.tencent.cloud.polaris.context.ServiceRuleManager;
|
||||
import com.tencent.polaris.client.pb.ModelProto;
|
||||
import com.tencent.polaris.client.pb.RateLimitProto;
|
||||
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
/**
|
||||
* resolve labels from rate limit rule.
|
||||
*
|
||||
*@author lepdou 2022-05-13
|
||||
*/
|
||||
public class RateLimitRuleLabelResolver {
|
||||
|
||||
private final ServiceRuleManager serviceRuleManager;
|
||||
|
||||
public RateLimitRuleLabelResolver(ServiceRuleManager serviceRuleManager) {
|
||||
this.serviceRuleManager = serviceRuleManager;
|
||||
}
|
||||
|
||||
public Set<String> getExpressionLabelKeys(String namespace, String service) {
|
||||
RateLimitProto.RateLimit rateLimitRule = serviceRuleManager.getServiceRateLimitRule(namespace, service);
|
||||
if (rateLimitRule == null) {
|
||||
return Collections.emptySet();
|
||||
}
|
||||
|
||||
List<RateLimitProto.Rule> rules = rateLimitRule.getRulesList();
|
||||
if (CollectionUtils.isEmpty(rules)) {
|
||||
return Collections.emptySet();
|
||||
}
|
||||
|
||||
Set<String> expressionLabels = new HashSet<>();
|
||||
for (RateLimitProto.Rule rule : rules) {
|
||||
Map<String, ModelProto.MatchString> labels = rule.getLabelsMap();
|
||||
if (CollectionUtils.isEmpty(labels)) {
|
||||
return Collections.emptySet();
|
||||
}
|
||||
for (String key : labels.keySet()) {
|
||||
if (ExpressionLabelUtils.isExpressionLabel(key)) {
|
||||
expressionLabels.add(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
return expressionLabels;
|
||||
}
|
||||
}
|
@ -0,0 +1,184 @@
|
||||
/*
|
||||
* 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;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import com.netflix.client.config.IClientConfig;
|
||||
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
|
||||
import com.netflix.loadbalancer.AvailabilityFilteringRule;
|
||||
import com.netflix.loadbalancer.BestAvailableRule;
|
||||
import com.netflix.loadbalancer.ILoadBalancer;
|
||||
import com.netflix.loadbalancer.RandomRule;
|
||||
import com.netflix.loadbalancer.RetryRule;
|
||||
import com.netflix.loadbalancer.RoundRobinRule;
|
||||
import com.netflix.loadbalancer.Server;
|
||||
import com.netflix.loadbalancer.WeightedResponseTimeRule;
|
||||
import com.netflix.loadbalancer.ZoneAvoidanceRule;
|
||||
import com.tencent.cloud.common.metadata.MetadataContext;
|
||||
import com.tencent.cloud.common.pojo.PolarisServer;
|
||||
import com.tencent.cloud.polaris.loadbalancer.LoadBalancerUtils;
|
||||
import com.tencent.cloud.polaris.loadbalancer.PolarisWeightedRule;
|
||||
import com.tencent.cloud.polaris.loadbalancer.config.PolarisLoadBalancerProperties;
|
||||
import com.tencent.polaris.api.pojo.Instance;
|
||||
import com.tencent.polaris.api.pojo.ServiceInfo;
|
||||
import com.tencent.polaris.api.pojo.ServiceInstances;
|
||||
import com.tencent.polaris.router.api.core.RouterAPI;
|
||||
import com.tencent.polaris.router.api.rpc.ProcessRoutersRequest;
|
||||
import com.tencent.polaris.router.api.rpc.ProcessRoutersResponse;
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
/**
|
||||
*
|
||||
* Service routing entrance.
|
||||
*
|
||||
* Rule routing needs to rely on request parameters for server filtering,
|
||||
* and {@link com.netflix.loadbalancer.ServerListFilter#getFilteredListOfServers(List)}
|
||||
* The interface cannot obtain the context object of the request granularity,
|
||||
* so the routing capability cannot be achieved through ServerListFilter.
|
||||
*
|
||||
* And {@link com.netflix.loadbalancer.IRule#choose(Object)} provides the ability to pass in context parameters,
|
||||
* so routing capabilities are implemented through IRule.
|
||||
*
|
||||
* @author Haotian Zhang, lepdou
|
||||
*/
|
||||
public class PolarisLoadBalancerCompositeRule extends AbstractLoadBalancerRule {
|
||||
|
||||
private final static String STRATEGY_RANDOM = "random";
|
||||
private final static String STRATEGY_ROUND_ROBIN = "roundRobin";
|
||||
private final static String STRATEGY_WEIGHT = "polarisWeighted";
|
||||
private final static String STRATEGY_RETRY = "retry";
|
||||
private final static String STRATEGY_RESPONSE_TIME_WEIGHTED = "responseTimeWeighted";
|
||||
private final static String STRATEGY_BEST_AVAILABLE = "bestAvailable";
|
||||
private final static String STRATEGY_ZONE_AVOIDANCE = "zoneAvoidance";
|
||||
private final static String STRATEGY_AVAILABILITY_FILTERING = "availabilityFilteringRule";
|
||||
|
||||
private final PolarisLoadBalancerProperties loadBalancerProperties;
|
||||
private final RouterAPI routerAPI;
|
||||
|
||||
private final AbstractLoadBalancerRule delegateRule;
|
||||
|
||||
public PolarisLoadBalancerCompositeRule(RouterAPI routerAPI, PolarisLoadBalancerProperties polarisLoadBalancerProperties,
|
||||
IClientConfig iClientConfig) {
|
||||
this.routerAPI = routerAPI;
|
||||
this.loadBalancerProperties = polarisLoadBalancerProperties;
|
||||
|
||||
delegateRule = getRule();
|
||||
delegateRule.initWithNiwsConfig(iClientConfig);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void initWithNiwsConfig(IClientConfig clientConfig) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Server choose(Object key) {
|
||||
// 1. get all servers
|
||||
List<Server> allServers = getLoadBalancer().getReachableServers();
|
||||
if (CollectionUtils.isEmpty(allServers)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// 2. filter by router
|
||||
List<Server> serversAfterRouter = doRouter(allServers, key);
|
||||
|
||||
// 3. filter by load balance.
|
||||
// A LoadBalancer needs to be regenerated for each request,
|
||||
// because the list of servers may be different after filtered by router
|
||||
ILoadBalancer loadBalancer = new SimpleLoadBalancer();
|
||||
loadBalancer.addServers(serversAfterRouter);
|
||||
delegateRule.setLoadBalancer(loadBalancer);
|
||||
|
||||
return delegateRule.choose(key);
|
||||
}
|
||||
|
||||
private List<Server> doRouter(List<Server> allServers, Object key) {
|
||||
ServiceInstances serviceInstances = LoadBalancerUtils.transferServersToServiceInstances(allServers);
|
||||
|
||||
// filter instance by routers
|
||||
ProcessRoutersRequest processRoutersRequest = buildProcessRoutersRequest(serviceInstances, key);
|
||||
|
||||
ProcessRoutersResponse processRoutersResponse = routerAPI.processRouters(processRoutersRequest);
|
||||
|
||||
List<Server> filteredInstances = new ArrayList<>();
|
||||
ServiceInstances filteredServiceInstances = processRoutersResponse.getServiceInstances();
|
||||
for (Instance instance : filteredServiceInstances.getInstances()) {
|
||||
filteredInstances.add(new PolarisServer(serviceInstances, instance));
|
||||
}
|
||||
return filteredInstances;
|
||||
}
|
||||
|
||||
private ProcessRoutersRequest buildProcessRoutersRequest(ServiceInstances serviceInstances, Object key) {
|
||||
ProcessRoutersRequest processRoutersRequest = new ProcessRoutersRequest();
|
||||
processRoutersRequest.setDstInstances(serviceInstances);
|
||||
|
||||
Map<String, String> routerMetadata;
|
||||
if (key instanceof PolarisRouterContext) {
|
||||
routerMetadata = ((PolarisRouterContext) key).getLabels();
|
||||
}
|
||||
else {
|
||||
routerMetadata = Collections.emptyMap();
|
||||
}
|
||||
|
||||
String srcNamespace = MetadataContext.LOCAL_NAMESPACE;
|
||||
String srcService = MetadataContext.LOCAL_SERVICE;
|
||||
|
||||
if (StringUtils.isNotBlank(srcNamespace) && StringUtils.isNotBlank(srcService)) {
|
||||
ServiceInfo serviceInfo = new ServiceInfo();
|
||||
serviceInfo.setNamespace(srcNamespace);
|
||||
serviceInfo.setService(srcService);
|
||||
serviceInfo.setMetadata(routerMetadata);
|
||||
processRoutersRequest.setSourceService(serviceInfo);
|
||||
}
|
||||
|
||||
return processRoutersRequest;
|
||||
}
|
||||
|
||||
public AbstractLoadBalancerRule getRule() {
|
||||
String loadBalanceStrategy = loadBalancerProperties.getStrategy();
|
||||
if (org.springframework.util.StringUtils.isEmpty(loadBalanceStrategy)) {
|
||||
return new RoundRobinRule();
|
||||
}
|
||||
|
||||
switch (loadBalanceStrategy) {
|
||||
case STRATEGY_RANDOM:
|
||||
return new RandomRule();
|
||||
case STRATEGY_WEIGHT:
|
||||
return new PolarisWeightedRule(routerAPI);
|
||||
case STRATEGY_RETRY:
|
||||
return new RetryRule();
|
||||
case STRATEGY_RESPONSE_TIME_WEIGHTED:
|
||||
return new WeightedResponseTimeRule();
|
||||
case STRATEGY_BEST_AVAILABLE:
|
||||
return new BestAvailableRule();
|
||||
case STRATEGY_ROUND_ROBIN:
|
||||
return new RoundRobinRule();
|
||||
case STRATEGY_AVAILABILITY_FILTERING:
|
||||
return new AvailabilityFilteringRule();
|
||||
case STRATEGY_ZONE_AVOIDANCE:
|
||||
default:
|
||||
return new ZoneAvoidanceRule();
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,53 @@
|
||||
/*
|
||||
* 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;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
/**
|
||||
* the context for router.
|
||||
*
|
||||
*@author lepdou 2022-05-17
|
||||
*/
|
||||
public class PolarisRouterContext {
|
||||
|
||||
private Map<String, String> labels;
|
||||
|
||||
public Map<String, String> getLabels() {
|
||||
if (CollectionUtils.isEmpty(labels)) {
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
return Collections.unmodifiableMap(labels);
|
||||
}
|
||||
|
||||
public void setLabels(Map<String, String> labels) {
|
||||
this.labels = labels;
|
||||
}
|
||||
|
||||
public void putLabel(String key, String value) {
|
||||
if (labels == null) {
|
||||
labels = new HashMap<>();
|
||||
}
|
||||
labels.put(key, value);
|
||||
}
|
||||
}
|
@ -0,0 +1,75 @@
|
||||
/*
|
||||
* 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;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import com.tencent.cloud.common.util.ExpressionLabelUtils;
|
||||
import com.tencent.cloud.polaris.context.ServiceRuleManager;
|
||||
import com.tencent.polaris.client.pb.ModelProto;
|
||||
import com.tencent.polaris.client.pb.RoutingProto;
|
||||
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
/**
|
||||
* Resolve label expressions from routing rules.
|
||||
* @author lepdou 2022-05-19
|
||||
*/
|
||||
public class RouterRuleLabelResolver {
|
||||
|
||||
private final ServiceRuleManager serviceRuleManager;
|
||||
|
||||
public RouterRuleLabelResolver(ServiceRuleManager serviceRuleManager) {
|
||||
this.serviceRuleManager = serviceRuleManager;
|
||||
}
|
||||
|
||||
public Set<String> getExpressionLabelKeys(String namespace, String sourceService, String dstService) {
|
||||
List<RoutingProto.Route> rules = serviceRuleManager.getServiceRouterRule(namespace, sourceService, dstService);
|
||||
|
||||
if (CollectionUtils.isEmpty(rules)) {
|
||||
return Collections.emptySet();
|
||||
}
|
||||
|
||||
Set<String> expressionLabels = new HashSet<>();
|
||||
|
||||
for (RoutingProto.Route rule : rules) {
|
||||
List<RoutingProto.Source> sources = rule.getSourcesList();
|
||||
if (CollectionUtils.isEmpty(sources)) {
|
||||
continue;
|
||||
}
|
||||
for (RoutingProto.Source source : sources) {
|
||||
Map<String, ModelProto.MatchString> labels = source.getMetadataMap();
|
||||
if (CollectionUtils.isEmpty(labels)) {
|
||||
continue;
|
||||
}
|
||||
for (String labelKey : labels.keySet()) {
|
||||
if (ExpressionLabelUtils.isExpressionLabel(labelKey)) {
|
||||
expressionLabels.add(labelKey);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return expressionLabels;
|
||||
}
|
||||
}
|
@ -0,0 +1,63 @@
|
||||
/*
|
||||
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
|
||||
*
|
||||
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
|
||||
*
|
||||
* Licensed under the BSD 3-Clause License (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://opensource.org/licenses/BSD-3-Clause
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software distributed
|
||||
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
|
||||
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations under the License.
|
||||
*
|
||||
*/
|
||||
|
||||
package com.tencent.cloud.polaris.router;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.netflix.loadbalancer.ILoadBalancer;
|
||||
import com.netflix.loadbalancer.Server;
|
||||
|
||||
/**
|
||||
* Simple load balancer only for getting and setting servers.
|
||||
*
|
||||
*@author lepdou 2022-05-17
|
||||
*/
|
||||
public class SimpleLoadBalancer implements ILoadBalancer {
|
||||
private List<Server> servers;
|
||||
|
||||
@Override
|
||||
public void addServers(List<Server> newServers) {
|
||||
this.servers = newServers;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Server chooseServer(Object key) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void markServerDown(Server server) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Server> getServerList(boolean availableOnly) {
|
||||
return servers;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Server> getReachableServers() {
|
||||
return servers;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Server> getAllServers() {
|
||||
return servers;
|
||||
}
|
||||
}
|
@ -0,0 +1,44 @@
|
||||
/*
|
||||
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
|
||||
*
|
||||
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
|
||||
*
|
||||
* Licensed under the BSD 3-Clause License (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://opensource.org/licenses/BSD-3-Clause
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software distributed
|
||||
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
|
||||
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations under the License.
|
||||
*
|
||||
*/
|
||||
|
||||
package com.tencent.cloud.polaris.router.config;
|
||||
|
||||
import com.netflix.client.config.IClientConfig;
|
||||
import com.netflix.loadbalancer.ILoadBalancer;
|
||||
import com.tencent.cloud.polaris.router.feign.PolarisFeignLoadBalancer;
|
||||
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.cloud.netflix.ribbon.ServerIntrospector;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* configuration for feign component.
|
||||
*
|
||||
*@author lepdou 2022-05-16
|
||||
*/
|
||||
@Configuration
|
||||
public class FeignConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public PolarisFeignLoadBalancer polarisFeignLoadBalancer(ILoadBalancer lb, IClientConfig clientConfig,
|
||||
ServerIntrospector serverIntrospector) {
|
||||
return new PolarisFeignLoadBalancer(lb, clientConfig, serverIntrospector);
|
||||
}
|
||||
}
|
@ -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.router.config;
|
||||
|
||||
import com.netflix.client.config.IClientConfig;
|
||||
import com.netflix.loadbalancer.IRule;
|
||||
import com.tencent.cloud.polaris.loadbalancer.config.PolarisLoadBalancerProperties;
|
||||
import com.tencent.cloud.polaris.router.PolarisLoadBalancerCompositeRule;
|
||||
import com.tencent.polaris.router.api.core.RouterAPI;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* Auto configuration for ribbon components.
|
||||
* @author lepdou 2022-05-17
|
||||
*/
|
||||
@Configuration
|
||||
public class RibbonConfiguration {
|
||||
|
||||
@Bean
|
||||
public IRule polarisLoadBalancerCompositeRule(RouterAPI routerAPI,
|
||||
PolarisLoadBalancerProperties polarisLoadBalancerProperties,
|
||||
IClientConfig iClientConfig) {
|
||||
return new PolarisLoadBalancerCompositeRule(routerAPI, polarisLoadBalancerProperties, iClientConfig);
|
||||
}
|
||||
}
|
@ -0,0 +1,69 @@
|
||||
/*
|
||||
* 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.config;
|
||||
|
||||
import com.tencent.cloud.common.metadata.config.MetadataLocalProperties;
|
||||
import com.tencent.cloud.polaris.context.ServiceRuleManager;
|
||||
import com.tencent.cloud.polaris.router.RouterRuleLabelResolver;
|
||||
import com.tencent.cloud.polaris.router.feign.PolarisCachingSpringLoadBalanceFactory;
|
||||
import com.tencent.cloud.polaris.router.feign.RouterLabelInterceptor;
|
||||
import com.tencent.cloud.polaris.router.resttemplate.PolarisLoadBalancerBeanPostProcessor;
|
||||
import com.tencent.cloud.polaris.router.spi.RouterLabelResolver;
|
||||
|
||||
import org.springframework.cloud.netflix.ribbon.RibbonClients;
|
||||
import org.springframework.cloud.netflix.ribbon.SpringClientFactory;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.lang.Nullable;
|
||||
|
||||
import static org.springframework.core.Ordered.HIGHEST_PRECEDENCE;
|
||||
|
||||
/**
|
||||
* router module auto configuration.
|
||||
*
|
||||
*@author lepdou 2022-05-11
|
||||
*/
|
||||
@Configuration
|
||||
@RibbonClients(defaultConfiguration = {FeignConfiguration.class, RibbonConfiguration.class})
|
||||
public class RouterAutoConfiguration {
|
||||
|
||||
@Bean
|
||||
public RouterLabelInterceptor routerLabelInterceptor(@Nullable RouterLabelResolver resolver,
|
||||
MetadataLocalProperties metadataLocalProperties,
|
||||
RouterRuleLabelResolver routerRuleLabelResolver) {
|
||||
return new RouterLabelInterceptor(resolver, metadataLocalProperties, routerRuleLabelResolver);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PolarisCachingSpringLoadBalanceFactory polarisCachingSpringLoadBalanceFactory(SpringClientFactory factory) {
|
||||
return new PolarisCachingSpringLoadBalanceFactory(factory);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Order(HIGHEST_PRECEDENCE)
|
||||
public PolarisLoadBalancerBeanPostProcessor polarisLoadBalancerBeanPostProcessor() {
|
||||
return new PolarisLoadBalancerBeanPostProcessor();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public RouterRuleLabelResolver routerRuleLabelResolver(ServiceRuleManager serviceRuleManager) {
|
||||
return new RouterRuleLabelResolver(serviceRuleManager);
|
||||
}
|
||||
}
|
@ -0,0 +1,81 @@
|
||||
/*
|
||||
* 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.feign;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import com.tencent.cloud.common.util.ExpressionLabelUtils;
|
||||
import feign.RequestTemplate;
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
/**
|
||||
* Resolve rule expression label from feign request.
|
||||
* @author lepdou 2022-05-20
|
||||
*/
|
||||
public class FeignExpressionLabelUtils {
|
||||
|
||||
public static Map<String, String> resolve(RequestTemplate request, Set<String> labelKeys) {
|
||||
if (CollectionUtils.isEmpty(labelKeys)) {
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
|
||||
Map<String, String> labels = new HashMap<>();
|
||||
|
||||
for (String labelKey : labelKeys) {
|
||||
if (StringUtils.startsWithIgnoreCase(labelKey, ExpressionLabelUtils.LABEL_HEADER_PREFIX)) {
|
||||
String headerKey = ExpressionLabelUtils.parseHeaderKey(labelKey);
|
||||
if (StringUtils.isBlank(headerKey)) {
|
||||
continue;
|
||||
}
|
||||
labels.put(labelKey, getHeaderValue(request, headerKey));
|
||||
}
|
||||
else if (StringUtils.startsWithIgnoreCase(labelKey, ExpressionLabelUtils.LABEL_QUERY_PREFIX)) {
|
||||
String queryKey = ExpressionLabelUtils.parseQueryKey(labelKey);
|
||||
if (StringUtils.isBlank(queryKey)) {
|
||||
continue;
|
||||
}
|
||||
labels.put(labelKey, getQueryValue(request, queryKey));
|
||||
}
|
||||
else if (StringUtils.equalsIgnoreCase(ExpressionLabelUtils.LABEL_METHOD, labelKey)) {
|
||||
labels.put(labelKey, request.method());
|
||||
}
|
||||
else if (StringUtils.equalsIgnoreCase(ExpressionLabelUtils.LABEL_URI, labelKey)) {
|
||||
labels.put(labelKey, request.request().url());
|
||||
}
|
||||
}
|
||||
|
||||
return labels;
|
||||
}
|
||||
|
||||
public static String getHeaderValue(RequestTemplate request, String key) {
|
||||
Map<String, Collection<String>> headers = request.headers();
|
||||
return ExpressionLabelUtils.getFirstValue(headers, key);
|
||||
|
||||
}
|
||||
|
||||
public static String getQueryValue(RequestTemplate request, String key) {
|
||||
return ExpressionLabelUtils.getFirstValue(request.queries(), key);
|
||||
}
|
||||
}
|
@ -0,0 +1,72 @@
|
||||
/*
|
||||
* 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.feign;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import com.netflix.client.config.IClientConfig;
|
||||
import com.netflix.loadbalancer.ILoadBalancer;
|
||||
|
||||
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory;
|
||||
import org.springframework.cloud.netflix.ribbon.ServerIntrospector;
|
||||
import org.springframework.cloud.netflix.ribbon.SpringClientFactory;
|
||||
import org.springframework.cloud.openfeign.ribbon.CachingSpringLoadBalancerFactory;
|
||||
import org.springframework.cloud.openfeign.ribbon.FeignLoadBalancer;
|
||||
import org.springframework.util.ConcurrentReferenceHashMap;
|
||||
|
||||
/**
|
||||
* Extends CachingSpringLoadBalancerFactory to be able to create PolarisFeignLoadBalance.
|
||||
*
|
||||
*@author lepdou 2022-05-16
|
||||
*/
|
||||
public class PolarisCachingSpringLoadBalanceFactory extends CachingSpringLoadBalancerFactory {
|
||||
|
||||
private final Map<String, FeignLoadBalancer> cache = new ConcurrentReferenceHashMap<>();
|
||||
|
||||
public PolarisCachingSpringLoadBalanceFactory(SpringClientFactory factory) {
|
||||
super(factory);
|
||||
}
|
||||
|
||||
public PolarisCachingSpringLoadBalanceFactory(SpringClientFactory factory,
|
||||
LoadBalancedRetryFactory loadBalancedRetryPolicyFactory) {
|
||||
super(factory, loadBalancedRetryPolicyFactory);
|
||||
}
|
||||
|
||||
@Override
|
||||
public FeignLoadBalancer create(String clientName) {
|
||||
FeignLoadBalancer client = this.cache.get(clientName);
|
||||
if (client != null) {
|
||||
return client;
|
||||
}
|
||||
|
||||
IClientConfig config = this.factory.getClientConfig(clientName);
|
||||
ILoadBalancer lb = this.factory.getLoadBalancer(clientName);
|
||||
ServerIntrospector serverIntrospector = this.factory.getInstance(clientName, ServerIntrospector.class);
|
||||
|
||||
FeignLoadBalancer loadBalancer = new PolarisFeignLoadBalancer(lb, config, serverIntrospector);
|
||||
|
||||
//There is a concurrency problem here.
|
||||
//When the concurrency is high, it may cause a service to create multiple FeignLoadBalancers.
|
||||
//But there is no concurrency control in CachingSpringLoadBalancerFactory,
|
||||
//so no locks will be added here for the time being
|
||||
cache.putIfAbsent(clientName, loadBalancer);
|
||||
|
||||
return loadBalancer;
|
||||
}
|
||||
}
|
@ -0,0 +1,76 @@
|
||||
/*
|
||||
* 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.feign;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import com.netflix.client.config.IClientConfig;
|
||||
import com.netflix.loadbalancer.ILoadBalancer;
|
||||
import com.netflix.loadbalancer.reactive.LoadBalancerCommand;
|
||||
import com.tencent.cloud.common.util.ExpressionLabelUtils;
|
||||
import com.tencent.cloud.common.util.JacksonUtils;
|
||||
import com.tencent.cloud.polaris.router.PolarisRouterContext;
|
||||
import com.tencent.cloud.polaris.router.RouterConstants;
|
||||
|
||||
import org.springframework.cloud.netflix.ribbon.ServerIntrospector;
|
||||
import org.springframework.cloud.openfeign.ribbon.FeignLoadBalancer;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
/**
|
||||
* In order to pass router context for {@link com.tencent.cloud.polaris.router.PolarisLoadBalancerCompositeRule}.
|
||||
*
|
||||
*@author lepdou 2022-05-16
|
||||
*/
|
||||
public class PolarisFeignLoadBalancer extends FeignLoadBalancer {
|
||||
|
||||
public PolarisFeignLoadBalancer(ILoadBalancer lb, IClientConfig clientConfig, ServerIntrospector serverIntrospector) {
|
||||
super(lb, clientConfig, serverIntrospector);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void customizeLoadBalancerCommandBuilder(RibbonRequest request, IClientConfig config,
|
||||
LoadBalancerCommand.Builder<RibbonResponse> builder) {
|
||||
Map<String, Collection<String>> headers = request.getRequest().headers();
|
||||
Collection<String> labelHeaderValues = headers.get(RouterConstants.ROUTER_LABEL_HEADER);
|
||||
|
||||
if (CollectionUtils.isEmpty(labelHeaderValues)) {
|
||||
builder.withServerLocator(null);
|
||||
return;
|
||||
}
|
||||
|
||||
PolarisRouterContext routerContext = new PolarisRouterContext();
|
||||
|
||||
labelHeaderValues.forEach(labelHeaderValue -> {
|
||||
Map<String, String> labels = JacksonUtils.deserialize2Map(labelHeaderValue);
|
||||
if (!CollectionUtils.isEmpty(labels)) {
|
||||
Map<String, String> unescapeLabels = new HashMap<>(labels.size());
|
||||
for (Map.Entry<String, String> entry : labels.entrySet()) {
|
||||
String escapedKey = ExpressionLabelUtils.unescape(entry.getKey());
|
||||
String escapedValue = ExpressionLabelUtils.unescape(entry.getValue());
|
||||
unescapeLabels.put(escapedKey, escapedValue);
|
||||
}
|
||||
routerContext.setLabels(unescapeLabels);
|
||||
}
|
||||
});
|
||||
|
||||
builder.withServerLocator(routerContext);
|
||||
}
|
||||
}
|
@ -0,0 +1,123 @@
|
||||
/*
|
||||
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
|
||||
*
|
||||
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
|
||||
*
|
||||
* Licensed under the BSD 3-Clause License (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://opensource.org/licenses/BSD-3-Clause
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software distributed
|
||||
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
|
||||
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations under the License.
|
||||
*
|
||||
*/
|
||||
|
||||
package com.tencent.cloud.polaris.router.feign;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import com.tencent.cloud.common.metadata.MetadataContext;
|
||||
import com.tencent.cloud.common.metadata.MetadataContextHolder;
|
||||
import com.tencent.cloud.common.metadata.config.MetadataLocalProperties;
|
||||
import com.tencent.cloud.common.util.ExpressionLabelUtils;
|
||||
import com.tencent.cloud.common.util.JacksonUtils;
|
||||
import com.tencent.cloud.polaris.router.RouterConstants;
|
||||
import com.tencent.cloud.polaris.router.RouterRuleLabelResolver;
|
||||
import com.tencent.cloud.polaris.router.spi.RouterLabelResolver;
|
||||
import feign.RequestInterceptor;
|
||||
import feign.RequestTemplate;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
/**
|
||||
* Resolver labels from request.
|
||||
*
|
||||
*@author lepdou 2022-05-12
|
||||
*/
|
||||
public class RouterLabelInterceptor implements RequestInterceptor, Ordered {
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(RouterLabelInterceptor.class);
|
||||
|
||||
private final RouterLabelResolver resolver;
|
||||
private final MetadataLocalProperties metadataLocalProperties;
|
||||
private final RouterRuleLabelResolver routerRuleLabelResolver;
|
||||
|
||||
public RouterLabelInterceptor(RouterLabelResolver resolver,
|
||||
MetadataLocalProperties metadataLocalProperties,
|
||||
RouterRuleLabelResolver routerRuleLabelResolver) {
|
||||
this.resolver = resolver;
|
||||
this.metadataLocalProperties = metadataLocalProperties;
|
||||
this.routerRuleLabelResolver = routerRuleLabelResolver;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getOrder() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void apply(RequestTemplate requestTemplate) {
|
||||
Map<String, String> labels = new HashMap<>();
|
||||
|
||||
// labels from downstream
|
||||
Map<String, String> transitiveLabels = MetadataContextHolder.get()
|
||||
.getFragmentContext(MetadataContext.FRAGMENT_TRANSITIVE);
|
||||
labels.putAll(transitiveLabels);
|
||||
|
||||
// labels from request
|
||||
if (resolver != null) {
|
||||
try {
|
||||
Map<String, String> customResolvedLabels = resolver.resolve(requestTemplate);
|
||||
if (!CollectionUtils.isEmpty(customResolvedLabels)) {
|
||||
labels.putAll(customResolvedLabels);
|
||||
}
|
||||
}
|
||||
catch (Throwable t) {
|
||||
LOGGER.error("[SCT][Router] revoke RouterLabelResolver occur some exception. ", t);
|
||||
}
|
||||
}
|
||||
|
||||
// labels from rule expression
|
||||
String peerServiceName = requestTemplate.feignTarget().name();
|
||||
Map<String, String> ruleExpressionLabels = getRuleExpressionLabels(requestTemplate, peerServiceName);
|
||||
labels.putAll(ruleExpressionLabels);
|
||||
|
||||
|
||||
//local service labels
|
||||
labels.putAll(metadataLocalProperties.getContent());
|
||||
|
||||
// Because when the label is placed in RequestTemplate.header,
|
||||
// RequestTemplate will parse the header according to the regular, which conflicts with the expression.
|
||||
// Avoid conflicts by escaping.
|
||||
Map<String, String> escapeLabels = new HashMap<>(labels.size());
|
||||
for (Map.Entry<String, String> entry : labels.entrySet()) {
|
||||
String escapedKey = ExpressionLabelUtils.escape(entry.getKey());
|
||||
String escapedValue = ExpressionLabelUtils.escape(entry.getValue());
|
||||
escapeLabels.put(escapedKey, escapedValue);
|
||||
}
|
||||
|
||||
// pass label by header
|
||||
requestTemplate.header(RouterConstants.ROUTER_LABEL_HEADER, JacksonUtils.serialize2Json(escapeLabels));
|
||||
}
|
||||
|
||||
private Map<String, String> getRuleExpressionLabels(RequestTemplate requestTemplate, String peerService) {
|
||||
Set<String> labelKeys = routerRuleLabelResolver.getExpressionLabelKeys(MetadataContext.LOCAL_NAMESPACE,
|
||||
MetadataContext.LOCAL_SERVICE, peerService);
|
||||
|
||||
if (CollectionUtils.isEmpty(labelKeys)) {
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
|
||||
return FeignExpressionLabelUtils.resolve(requestTemplate, labelKeys);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,62 @@
|
||||
/*
|
||||
* 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 com.tencent.cloud.common.metadata.config.MetadataLocalProperties;
|
||||
import com.tencent.cloud.polaris.router.RouterRuleLabelResolver;
|
||||
import com.tencent.cloud.polaris.router.spi.RouterLabelResolver;
|
||||
|
||||
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 PolarisLoadBalancerBeanPostProcessor 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);
|
||||
RouterLabelResolver routerLabelResolver = this.factory.getBean(RouterLabelResolver.class);
|
||||
MetadataLocalProperties metadataLocalProperties = this.factory.getBean(MetadataLocalProperties.class);
|
||||
RouterRuleLabelResolver routerRuleLabelResolver = this.factory.getBean(RouterRuleLabelResolver.class);
|
||||
|
||||
return new PolarisLoadBalancerInterceptor(loadBalancerClient, requestFactory,
|
||||
routerLabelResolver, metadataLocalProperties, routerRuleLabelResolver);
|
||||
}
|
||||
return bean;
|
||||
}
|
||||
}
|
@ -0,0 +1,143 @@
|
||||
/*
|
||||
* 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.net.URI;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import com.tencent.cloud.common.metadata.MetadataContext;
|
||||
import com.tencent.cloud.common.metadata.MetadataContextHolder;
|
||||
import com.tencent.cloud.common.metadata.config.MetadataLocalProperties;
|
||||
import com.tencent.cloud.common.util.ExpressionLabelUtils;
|
||||
import com.tencent.cloud.polaris.router.PolarisRouterContext;
|
||||
import com.tencent.cloud.polaris.router.RouterRuleLabelResolver;
|
||||
import com.tencent.cloud.polaris.router.spi.RouterLabelResolver;
|
||||
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.cloud.netflix.ribbon.RibbonLoadBalancerClient;
|
||||
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;
|
||||
|
||||
/**
|
||||
* PolarisLoadBalancerInterceptor extends LoadBalancerInterceptor capabilities.
|
||||
* Parses the label from the request and puts it into the RouterContext for routing.
|
||||
*
|
||||
*@author lepdou 2022-05-18
|
||||
*/
|
||||
public class PolarisLoadBalancerInterceptor extends LoadBalancerInterceptor {
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(PolarisLoadBalancerInterceptor.class);
|
||||
|
||||
private final LoadBalancerClient loadBalancer;
|
||||
private final LoadBalancerRequestFactory requestFactory;
|
||||
private final RouterLabelResolver resolver;
|
||||
private final MetadataLocalProperties metadataLocalProperties;
|
||||
private final RouterRuleLabelResolver routerRuleLabelResolver;
|
||||
|
||||
private final boolean isRibbonLoadBalanceClient;
|
||||
|
||||
public PolarisLoadBalancerInterceptor(LoadBalancerClient loadBalancer,
|
||||
LoadBalancerRequestFactory requestFactory,
|
||||
RouterLabelResolver resolver,
|
||||
MetadataLocalProperties metadataLocalProperties,
|
||||
RouterRuleLabelResolver routerRuleLabelResolver) {
|
||||
super(loadBalancer, requestFactory);
|
||||
this.loadBalancer = loadBalancer;
|
||||
this.requestFactory = requestFactory;
|
||||
this.resolver = resolver;
|
||||
this.metadataLocalProperties = metadataLocalProperties;
|
||||
this.routerRuleLabelResolver = routerRuleLabelResolver;
|
||||
|
||||
this.isRibbonLoadBalanceClient = loadBalancer instanceof RibbonLoadBalancerClient;
|
||||
}
|
||||
|
||||
@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);
|
||||
|
||||
if (isRibbonLoadBalanceClient) {
|
||||
PolarisRouterContext routerContext = genRouterContext(request, body, peerServiceName);
|
||||
|
||||
return ((RibbonLoadBalancerClient) loadBalancer).execute(peerServiceName,
|
||||
this.requestFactory.createRequest(request, body, execution), routerContext);
|
||||
}
|
||||
|
||||
return this.loadBalancer.execute(peerServiceName,
|
||||
this.requestFactory.createRequest(request, body, execution));
|
||||
}
|
||||
|
||||
private PolarisRouterContext genRouterContext(HttpRequest request, byte[] body, String peerServiceName) {
|
||||
Map<String, String> labels = new HashMap<>();
|
||||
|
||||
// labels from downstream
|
||||
Map<String, String> transitiveLabels = MetadataContextHolder.get()
|
||||
.getFragmentContext(MetadataContext.FRAGMENT_TRANSITIVE);
|
||||
labels.putAll(transitiveLabels);
|
||||
|
||||
// labels from request
|
||||
if (resolver != null) {
|
||||
try {
|
||||
Map<String, String> customResolvedLabels = resolver.resolve(request, body);
|
||||
if (!CollectionUtils.isEmpty(customResolvedLabels)) {
|
||||
labels.putAll(customResolvedLabels);
|
||||
}
|
||||
}
|
||||
catch (Throwable t) {
|
||||
LOGGER.error("[SCT][Router] revoke RouterLabelResolver occur some exception. ", t);
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, String> ruleExpressionLabels = getExpressionLabels(request, peerServiceName);
|
||||
if (!CollectionUtils.isEmpty(ruleExpressionLabels)) {
|
||||
labels.putAll(ruleExpressionLabels);
|
||||
}
|
||||
|
||||
//local service labels
|
||||
labels.putAll(metadataLocalProperties.getContent());
|
||||
|
||||
PolarisRouterContext routerContext = new PolarisRouterContext();
|
||||
routerContext.setLabels(labels);
|
||||
|
||||
return routerContext;
|
||||
}
|
||||
|
||||
private Map<String, String> getExpressionLabels(HttpRequest request, String peerServiceName) {
|
||||
Set<String> labelKeys = routerRuleLabelResolver.getExpressionLabelKeys(MetadataContext.LOCAL_NAMESPACE,
|
||||
MetadataContext.LOCAL_SERVICE, peerServiceName);
|
||||
|
||||
if (CollectionUtils.isEmpty(labelKeys)) {
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
|
||||
return ExpressionLabelUtils.resolve(request, labelKeys);
|
||||
}
|
||||
}
|
@ -0,0 +1,48 @@
|
||||
/*
|
||||
* 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.spi;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import feign.RequestTemplate;
|
||||
|
||||
import org.springframework.http.HttpRequest;
|
||||
|
||||
/**
|
||||
* The spi for resolving labels from request.
|
||||
*
|
||||
* @author lepdou 2022-05-11
|
||||
*/
|
||||
public interface RouterLabelResolver {
|
||||
|
||||
/**
|
||||
* resolve labels from feign request.
|
||||
* @param requestTemplate the feign request.
|
||||
* @return resolved labels
|
||||
*/
|
||||
Map<String, String> resolve(RequestTemplate requestTemplate);
|
||||
|
||||
/**
|
||||
* resolve labels from rest template request.
|
||||
* @param request the rest template request.
|
||||
* @param body the rest template request body.
|
||||
* @return resolved labels
|
||||
*/
|
||||
Map<String, String> resolve(HttpRequest request, byte[] body);
|
||||
}
|
@ -0,0 +1,2 @@
|
||||
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
|
||||
com.tencent.cloud.polaris.router.config.RouterAutoConfiguration
|
@ -0,0 +1,323 @@
|
||||
/*
|
||||
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
|
||||
*
|
||||
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
|
||||
*
|
||||
* Licensed under the BSD 3-Clause License (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://opensource.org/licenses/BSD-3-Clause
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software distributed
|
||||
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
|
||||
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations under the License.
|
||||
*
|
||||
*/
|
||||
|
||||
package com.tencent.cloud.common.util;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import javax.servlet.http.Cookie;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
|
||||
import org.springframework.http.HttpCookie;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpRequest;
|
||||
import org.springframework.http.server.reactive.ServerHttpRequest;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
import org.springframework.util.MultiValueMap;
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
|
||||
/**
|
||||
* the utils for parse label expression.
|
||||
*
|
||||
*@author lepdou 2022-05-13
|
||||
*/
|
||||
public class ExpressionLabelUtils {
|
||||
|
||||
/**
|
||||
* the expression prefix of header label.
|
||||
*/
|
||||
public static final String LABEL_HEADER_PREFIX = "${http.header.";
|
||||
/**
|
||||
* the length of expression header label prefix.
|
||||
*/
|
||||
public static final int LABEL_HEADER_PREFIX_LEN = LABEL_HEADER_PREFIX.length();
|
||||
/**
|
||||
* the expression prefix of query.
|
||||
*/
|
||||
public static final String LABEL_QUERY_PREFIX = "${http.query.";
|
||||
/**
|
||||
* the length of expression query label prefix.
|
||||
*/
|
||||
public static final int LABEL_QUERY_PREFIX_LEN = LABEL_QUERY_PREFIX.length();
|
||||
/**
|
||||
* the expression prefix of cookie.
|
||||
*/
|
||||
public static final String LABEL_COOKIE_PREFIX = "${http.cookie.";
|
||||
/**
|
||||
* the length of expression cookie label prefix.
|
||||
*/
|
||||
public static final int LABEL_COOKIE_PREFIX_LEN = LABEL_COOKIE_PREFIX.length();
|
||||
/**
|
||||
* the expression of method.
|
||||
*/
|
||||
public static final String LABEL_METHOD = "${http.method}";
|
||||
/**
|
||||
* the expression of uri.
|
||||
*/
|
||||
public static final String LABEL_URI = "${http.uri}";
|
||||
/**
|
||||
* the prefix of expression.
|
||||
*/
|
||||
public static final String LABEL_PREFIX = "${";
|
||||
/**
|
||||
* the suffix of expression.
|
||||
*/
|
||||
public static final String LABEL_SUFFIX = "}";
|
||||
/**
|
||||
* the escape prefix of label.
|
||||
*/
|
||||
public static final String LABEL_ESCAPE_PREFIX = "$$$$";
|
||||
|
||||
public static boolean isExpressionLabel(String labelKey) {
|
||||
if (StringUtils.isEmpty(labelKey)) {
|
||||
return false;
|
||||
}
|
||||
if (StringUtils.equalsIgnoreCase(LABEL_METHOD, labelKey) ||
|
||||
StringUtils.startsWithIgnoreCase(LABEL_URI, labelKey)) {
|
||||
return true;
|
||||
}
|
||||
return (StringUtils.startsWithIgnoreCase(labelKey, LABEL_HEADER_PREFIX) ||
|
||||
StringUtils.startsWithIgnoreCase(labelKey, LABEL_QUERY_PREFIX) ||
|
||||
StringUtils.startsWithIgnoreCase(labelKey, LABEL_COOKIE_PREFIX))
|
||||
&& StringUtils.endsWith(labelKey, LABEL_SUFFIX);
|
||||
}
|
||||
|
||||
public static String escape(String str) {
|
||||
return StringUtils.replace(str, LABEL_PREFIX, LABEL_ESCAPE_PREFIX);
|
||||
}
|
||||
|
||||
public static String unescape(String str) {
|
||||
return StringUtils.replace(str, LABEL_ESCAPE_PREFIX, LABEL_PREFIX);
|
||||
}
|
||||
|
||||
public static Map<String, String> resolve(HttpServletRequest request, Set<String> labelKeys) {
|
||||
if (CollectionUtils.isEmpty(labelKeys)) {
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
|
||||
Map<String, String> labels = new HashMap<>();
|
||||
|
||||
for (String labelKey : labelKeys) {
|
||||
if (StringUtils.startsWithIgnoreCase(labelKey, LABEL_HEADER_PREFIX)) {
|
||||
String headerKey = parseHeaderKey(labelKey);
|
||||
if (StringUtils.isBlank(headerKey)) {
|
||||
continue;
|
||||
}
|
||||
labels.put(labelKey, request.getHeader(headerKey));
|
||||
}
|
||||
else if (StringUtils.startsWithIgnoreCase(labelKey, LABEL_QUERY_PREFIX)) {
|
||||
String queryKey = parseQueryKey(labelKey);
|
||||
if (StringUtils.isBlank(queryKey)) {
|
||||
continue;
|
||||
}
|
||||
labels.put(labelKey, getQueryValue(request.getQueryString(), queryKey));
|
||||
}
|
||||
else if (StringUtils.startsWithIgnoreCase(labelKey, LABEL_COOKIE_PREFIX)) {
|
||||
String cookieKey = parseCookieKey(labelKey);
|
||||
if (StringUtils.isBlank(cookieKey)) {
|
||||
continue;
|
||||
}
|
||||
labels.put(labelKey, getCookieValue(request.getCookies(), cookieKey));
|
||||
}
|
||||
else if (StringUtils.equalsIgnoreCase(LABEL_METHOD, labelKey)) {
|
||||
labels.put(labelKey, request.getMethod());
|
||||
}
|
||||
else if (StringUtils.equalsIgnoreCase(LABEL_URI, labelKey)) {
|
||||
labels.put(labelKey, request.getRequestURI());
|
||||
}
|
||||
}
|
||||
|
||||
return labels;
|
||||
}
|
||||
|
||||
public static Map<String, String> resolve(ServerWebExchange exchange, Set<String> labelKeys) {
|
||||
if (CollectionUtils.isEmpty(labelKeys)) {
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
|
||||
Map<String, String> labels = new HashMap<>();
|
||||
|
||||
for (String labelKey : labelKeys) {
|
||||
if (StringUtils.startsWithIgnoreCase(labelKey, LABEL_HEADER_PREFIX)) {
|
||||
String headerKey = parseHeaderKey(labelKey);
|
||||
if (StringUtils.isBlank(headerKey)) {
|
||||
continue;
|
||||
}
|
||||
labels.put(labelKey, getHeaderValue(exchange.getRequest(), headerKey));
|
||||
}
|
||||
else if (StringUtils.startsWithIgnoreCase(labelKey, LABEL_QUERY_PREFIX)) {
|
||||
String queryKey = parseQueryKey(labelKey);
|
||||
if (StringUtils.isBlank(queryKey)) {
|
||||
continue;
|
||||
}
|
||||
labels.put(labelKey, getQueryValue(exchange.getRequest(), queryKey));
|
||||
}
|
||||
else if (StringUtils.startsWithIgnoreCase(labelKey, LABEL_COOKIE_PREFIX)) {
|
||||
String cookieKey = parseCookieKey(labelKey);
|
||||
if (StringUtils.isBlank(cookieKey)) {
|
||||
continue;
|
||||
}
|
||||
labels.put(labelKey, getCookieValue(exchange.getRequest(), cookieKey));
|
||||
}
|
||||
else if (StringUtils.equalsIgnoreCase(LABEL_METHOD, labelKey)) {
|
||||
labels.put(labelKey, exchange.getRequest().getMethodValue());
|
||||
}
|
||||
else if (StringUtils.equalsIgnoreCase(LABEL_URI, labelKey)) {
|
||||
labels.put(labelKey, exchange.getRequest().getURI().getPath());
|
||||
}
|
||||
}
|
||||
|
||||
return labels;
|
||||
}
|
||||
|
||||
public static Map<String, String> resolve(HttpRequest request, Set<String> labelKeys) {
|
||||
if (CollectionUtils.isEmpty(labelKeys)) {
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
|
||||
Map<String, String> labels = new HashMap<>();
|
||||
|
||||
for (String labelKey : labelKeys) {
|
||||
if (StringUtils.startsWithIgnoreCase(labelKey, LABEL_HEADER_PREFIX)) {
|
||||
String headerKey = parseHeaderKey(labelKey);
|
||||
if (StringUtils.isBlank(headerKey)) {
|
||||
continue;
|
||||
}
|
||||
labels.put(labelKey, getHeaderValue(request, headerKey));
|
||||
}
|
||||
else if (StringUtils.startsWithIgnoreCase(labelKey, LABEL_QUERY_PREFIX)) {
|
||||
String queryKey = parseQueryKey(labelKey);
|
||||
if (StringUtils.isBlank(queryKey)) {
|
||||
continue;
|
||||
}
|
||||
labels.put(labelKey, getQueryValue(request, queryKey));
|
||||
}
|
||||
else if (StringUtils.equalsIgnoreCase(LABEL_METHOD, labelKey)) {
|
||||
labels.put(labelKey, request.getMethodValue());
|
||||
}
|
||||
else if (StringUtils.equalsIgnoreCase(LABEL_URI, labelKey)) {
|
||||
labels.put(labelKey, request.getURI().getPath());
|
||||
}
|
||||
}
|
||||
|
||||
return labels;
|
||||
}
|
||||
|
||||
public static String parseHeaderKey(String expression) {
|
||||
return expression.substring(LABEL_HEADER_PREFIX_LEN, expression.length() - 1);
|
||||
}
|
||||
|
||||
public static String parseQueryKey(String expression) {
|
||||
return expression.substring(LABEL_QUERY_PREFIX_LEN, expression.length() - 1);
|
||||
}
|
||||
|
||||
public static String parseCookieKey(String expression) {
|
||||
return expression.substring(LABEL_COOKIE_PREFIX_LEN, expression.length() - 1);
|
||||
}
|
||||
|
||||
public static String getQueryValue(String queryString, String queryKey) {
|
||||
if (StringUtils.isBlank(queryString)) {
|
||||
return StringUtils.EMPTY;
|
||||
}
|
||||
String[] queries = StringUtils.split(queryString, "&");
|
||||
if (queries == null || queries.length == 0) {
|
||||
return StringUtils.EMPTY;
|
||||
}
|
||||
for (String query : queries) {
|
||||
String[] queryKV = StringUtils.split(query, "=");
|
||||
if (queryKV != null && queryKV.length == 2 && StringUtils.equals(queryKV[0], queryKey)) {
|
||||
return queryKV[1];
|
||||
}
|
||||
}
|
||||
return StringUtils.EMPTY;
|
||||
}
|
||||
|
||||
public static String getCookieValue(Cookie[] cookies, String key) {
|
||||
if (cookies == null || cookies.length == 0) {
|
||||
return StringUtils.EMPTY;
|
||||
}
|
||||
for (Cookie cookie : cookies) {
|
||||
if (StringUtils.equals(cookie.getName(), key)) {
|
||||
return cookie.getValue();
|
||||
}
|
||||
}
|
||||
return StringUtils.EMPTY;
|
||||
}
|
||||
|
||||
public static String getHeaderValue(ServerHttpRequest request, String key) {
|
||||
String value = request.getHeaders().getFirst(key);
|
||||
if (value == null) {
|
||||
return StringUtils.EMPTY;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
public static String getQueryValue(ServerHttpRequest request, String key) {
|
||||
MultiValueMap<String, String> queries = request.getQueryParams();
|
||||
if (CollectionUtils.isEmpty(queries)) {
|
||||
return StringUtils.EMPTY;
|
||||
}
|
||||
String value = queries.getFirst(key);
|
||||
if (value == null) {
|
||||
return StringUtils.EMPTY;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
public static String getCookieValue(ServerHttpRequest request, String key) {
|
||||
HttpCookie cookie = request.getCookies().getFirst(key);
|
||||
if (cookie == null) {
|
||||
return StringUtils.EMPTY;
|
||||
}
|
||||
return cookie.getValue();
|
||||
}
|
||||
|
||||
public static String getHeaderValue(HttpRequest request, String key) {
|
||||
HttpHeaders headers = request.getHeaders();
|
||||
return headers.getFirst(key);
|
||||
}
|
||||
|
||||
public static String getQueryValue(HttpRequest request, String key) {
|
||||
String query = request.getURI().getQuery();
|
||||
return getQueryValue(query, key);
|
||||
}
|
||||
|
||||
public static String getFirstValue(Map<String, Collection<String>> valueMaps, String key) {
|
||||
if (CollectionUtils.isEmpty(valueMaps)) {
|
||||
return StringUtils.EMPTY;
|
||||
}
|
||||
|
||||
Collection<String> values = valueMaps.get(key);
|
||||
|
||||
if (CollectionUtils.isEmpty(values)) {
|
||||
return StringUtils.EMPTY;
|
||||
}
|
||||
|
||||
for (String value : values) {
|
||||
return value;
|
||||
}
|
||||
|
||||
return StringUtils.EMPTY;
|
||||
}
|
||||
}
|
@ -0,0 +1,51 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<parent>
|
||||
<artifactId>metadata-transfer-example</artifactId>
|
||||
<groupId>com.tencent.cloud</groupId>
|
||||
<version>${revision}</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<artifactId>metadata-callee-service</artifactId>
|
||||
<name>Spring Cloud Tencent Metadata Transfer Callee Service</name>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.tencent.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-tencent-polaris-discovery</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>repackage</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-source-plugin</artifactId>
|
||||
<version>3.2.0</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>attach-sources</id>
|
||||
<goals>
|
||||
<goal>jar</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
@ -0,0 +1,65 @@
|
||||
/*
|
||||
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
|
||||
*
|
||||
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
|
||||
*
|
||||
* Licensed under the BSD 3-Clause License (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://opensource.org/licenses/BSD-3-Clause
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software distributed
|
||||
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
|
||||
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations under the License.
|
||||
*/
|
||||
|
||||
package com.tencent.cloud.metadata.service.callee;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import com.tencent.cloud.common.metadata.MetadataContext;
|
||||
import com.tencent.cloud.common.metadata.MetadataContextHolder;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/**
|
||||
* Metadata callee controller.
|
||||
*
|
||||
* @author Palmer Xu
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/metadata/service/callee")
|
||||
public class MetadataCalleeController {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(MetadataCalleeController.class);
|
||||
|
||||
@Value("${server.port:0}")
|
||||
private int port;
|
||||
|
||||
/**
|
||||
* Get information of callee.
|
||||
* @return information of callee
|
||||
*/
|
||||
@GetMapping("/info")
|
||||
public Map<String, String> info() {
|
||||
LOG.info("Metadata Service Callee [{}] is called.", port);
|
||||
|
||||
// Get Custom Metadata From Context
|
||||
MetadataContext context = MetadataContextHolder.get();
|
||||
Map<String, String> customMetadataMap = context.getFragmentContext(MetadataContext.FRAGMENT_TRANSITIVE);
|
||||
|
||||
customMetadataMap.forEach((key, value) -> {
|
||||
LOG.info("Custom Metadata (Key-Value): {} : {}", key, value);
|
||||
});
|
||||
|
||||
return customMetadataMap;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,35 @@
|
||||
/*
|
||||
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
|
||||
*
|
||||
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
|
||||
*
|
||||
* Licensed under the BSD 3-Clause License (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://opensource.org/licenses/BSD-3-Clause
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software distributed
|
||||
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
|
||||
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations under the License.
|
||||
*/
|
||||
|
||||
package com.tencent.cloud.metadata.service.callee;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
/**
|
||||
* Metadata callee application.
|
||||
*
|
||||
* @author Palmer Xu
|
||||
*/
|
||||
@SpringBootApplication
|
||||
public class MetadataCalleeService {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(MetadataCalleeService.class, args);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,13 @@
|
||||
server:
|
||||
port: 48084
|
||||
spring:
|
||||
application:
|
||||
name: MetadataCalleeService
|
||||
cloud:
|
||||
polaris:
|
||||
address: grpc://127.0.0.1:8091
|
||||
namespace: default
|
||||
enabled: true
|
||||
discovery:
|
||||
enabled: true
|
||||
register: true
|
@ -0,0 +1,51 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<parent>
|
||||
<artifactId>metadata-transfer-example</artifactId>
|
||||
<groupId>com.tencent.cloud</groupId>
|
||||
<version>${revision}</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<artifactId>metadata-caller-service</artifactId>
|
||||
<name>Spring Cloud Tencent Metadata Transfer Caller Service</name>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.tencent.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-tencent-polaris-discovery</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>repackage</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-source-plugin</artifactId>
|
||||
<version>3.2.0</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>attach-sources</id>
|
||||
<goals>
|
||||
<goal>jar</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
@ -0,0 +1,41 @@
|
||||
/*
|
||||
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
|
||||
*
|
||||
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
|
||||
*
|
||||
* Licensed under the BSD 3-Clause License (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://opensource.org/licenses/BSD-3-Clause
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software distributed
|
||||
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
|
||||
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations under the License.
|
||||
*/
|
||||
|
||||
package com.tencent.cloud.metadata.service.caller;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.cloud.openfeign.FeignClient;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
|
||||
/**
|
||||
* Metadata callee feign client.
|
||||
*
|
||||
* @author Palmer Xu
|
||||
*/
|
||||
@FeignClient(value = "MetadataCalleeService",
|
||||
fallback = MetadataCalleeServiceFallback.class)
|
||||
public interface MetadataCalleeService {
|
||||
|
||||
/**
|
||||
* Get information of callee.
|
||||
* @return information of callee
|
||||
*/
|
||||
@GetMapping("/metadata/service/callee/info")
|
||||
Map<String, String> info();
|
||||
|
||||
}
|
@ -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.metadata.service.caller;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import com.google.common.collect.Maps;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* Metadata callee feign client fallback.
|
||||
*
|
||||
* @author Palmer Xu
|
||||
*/
|
||||
@Component
|
||||
public class MetadataCalleeServiceFallback implements MetadataCalleeService {
|
||||
|
||||
@Override
|
||||
public Map<String, String> info() {
|
||||
return Maps.newHashMap();
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,109 @@
|
||||
/*
|
||||
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
|
||||
*
|
||||
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
|
||||
*
|
||||
* Licensed under the BSD 3-Clause License (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://opensource.org/licenses/BSD-3-Clause
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software distributed
|
||||
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
|
||||
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations under the License.
|
||||
*/
|
||||
|
||||
package com.tencent.cloud.metadata.service.caller;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import com.google.common.collect.Maps;
|
||||
import com.tencent.cloud.common.metadata.MetadataContext;
|
||||
import com.tencent.cloud.common.metadata.MetadataContextHolder;
|
||||
import com.tencent.cloud.common.metadata.config.MetadataLocalProperties;
|
||||
|
||||
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;
|
||||
|
||||
/**
|
||||
* Metadata caller controller.
|
||||
*
|
||||
* @author Palmer Xu
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/metadata/service/caller")
|
||||
public class MetadataCallerController {
|
||||
|
||||
private final RestTemplate restTemplate;
|
||||
|
||||
private final MetadataCalleeService metadataCalleeService;
|
||||
|
||||
private final MetadataLocalProperties metadataLocalProperties;
|
||||
|
||||
public MetadataCallerController(RestTemplate restTemplate,
|
||||
MetadataCalleeService metadataCalleeService,
|
||||
MetadataLocalProperties metadataLocalProperties) {
|
||||
this.restTemplate = restTemplate;
|
||||
this.metadataCalleeService = metadataCalleeService;
|
||||
this.metadataLocalProperties = metadataLocalProperties;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get metadata info from remote service.
|
||||
* @return metadata map
|
||||
*/
|
||||
@GetMapping("/feign/info")
|
||||
public Map<String, Map<String, String>> feign() {
|
||||
Map<String, Map<String, String>> ret = Maps.newHashMap();
|
||||
|
||||
// Call remote service with feign client
|
||||
Map<String, String> calleeMetadata = metadataCalleeService.info();
|
||||
ret.put("callee-transitive-metadata", calleeMetadata);
|
||||
|
||||
// Get Custom Metadata From Context
|
||||
MetadataContext context = MetadataContextHolder.get();
|
||||
Map<String, String> callerTransitiveMetadata = context.getFragmentContext(MetadataContext.FRAGMENT_TRANSITIVE);
|
||||
ret.put("caller-transitive-metadata", callerTransitiveMetadata);
|
||||
ret.put("caller-metadata-contents", metadataLocalProperties.getContent());
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get metadata information of callee.
|
||||
* @return information of callee
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
@GetMapping("/rest/info")
|
||||
public Map<String, Map<String, String>> rest() {
|
||||
Map<String, Map<String, String>> ret = Maps.newHashMap();
|
||||
|
||||
// Call remote service with RestTemplate
|
||||
Map<String, String> calleeMetadata = restTemplate.getForObject(
|
||||
"http://MetadataCalleeService/metadata/service/callee/info",
|
||||
Map.class);
|
||||
ret.put("callee-transitive-metadata", calleeMetadata);
|
||||
|
||||
// Get Custom Metadata From Context
|
||||
MetadataContext context = MetadataContextHolder.get();
|
||||
Map<String, String> callerTransitiveMetadata = context.getFragmentContext(MetadataContext.FRAGMENT_TRANSITIVE);
|
||||
ret.put("caller-transitive-metadata", callerTransitiveMetadata);
|
||||
ret.put("caller-metadata-contents", metadataLocalProperties.getContent());
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
/**
|
||||
* health check.
|
||||
* @return health check info
|
||||
*/
|
||||
@GetMapping("/healthCheck")
|
||||
public String healthCheck() {
|
||||
return "pk ok";
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,48 @@
|
||||
/*
|
||||
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
|
||||
*
|
||||
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
|
||||
*
|
||||
* Licensed under the BSD 3-Clause License (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://opensource.org/licenses/BSD-3-Clause
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software distributed
|
||||
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
|
||||
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations under the License.
|
||||
*/
|
||||
|
||||
package com.tencent.cloud.metadata.service.caller;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
|
||||
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
|
||||
import org.springframework.cloud.openfeign.EnableFeignClients;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
/**
|
||||
* Metadata caller application.
|
||||
*
|
||||
* @author Palmer Xu
|
||||
*/
|
||||
@SpringBootApplication
|
||||
@EnableDiscoveryClient
|
||||
@EnableFeignClients
|
||||
public class MetadataCallerService {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(MetadataCallerService.class, args);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@LoadBalanced
|
||||
public RestTemplate restTemplate() {
|
||||
return new RestTemplate();
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,26 @@
|
||||
server:
|
||||
port: 48080
|
||||
spring:
|
||||
application:
|
||||
name: MetadataCallerService
|
||||
cloud:
|
||||
polaris:
|
||||
address: grpc://127.0.0.1:8091
|
||||
namespace: default
|
||||
enabled: true
|
||||
discovery:
|
||||
enabled: true
|
||||
register: true
|
||||
heartbeat-enabled: true
|
||||
health-check-url: /metadata/service/caller/healthCheck
|
||||
tencent:
|
||||
metadata:
|
||||
# Defined your metadata keys & values
|
||||
content:
|
||||
# Example: intransitive
|
||||
CUSTOM-METADATA-KEY-LOCAL: CUSTOM-VALUE-LOCAL
|
||||
# Example: transitive
|
||||
CUSTOM-METADATA-KEY-TRANSITIVE: CUSTOM-VALUE-TRANSITIVE
|
||||
# Assigned which metadata key-value will be passed along the link
|
||||
transitive:
|
||||
- CUSTOM-METADATA-KEY-TRANSITIVE
|
@ -0,0 +1,43 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<parent>
|
||||
<artifactId>spring-cloud-tencent-examples</artifactId>
|
||||
<groupId>com.tencent.cloud</groupId>
|
||||
<version>${revision}</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<artifactId>metadata-transfer-example</artifactId>
|
||||
<packaging>pom</packaging>
|
||||
<name>Spring Cloud Starter Tencent Metadata Transfer Example</name>
|
||||
|
||||
<modules>
|
||||
<module>metadata-callee-service</module>
|
||||
<module>metadata-caller-service</module>
|
||||
</modules>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-actuator</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-openfeign</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.tencent.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-tencent-metadata-transfer</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
@ -0,0 +1,53 @@
|
||||
/*
|
||||
* 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.example;
|
||||
|
||||
/**
|
||||
* demo object.
|
||||
* @author lepdou 2022-05-12
|
||||
*/
|
||||
public class User {
|
||||
|
||||
private String name;
|
||||
private int age;
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(int age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "User{" +
|
||||
"name='" + name + '\'' +
|
||||
", age=" + age +
|
||||
'}';
|
||||
}
|
||||
}
|
@ -0,0 +1,60 @@
|
||||
/*
|
||||
* 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.example;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.tencent.cloud.polaris.router.spi.RouterLabelResolver;
|
||||
import feign.RequestTemplate;
|
||||
|
||||
import org.springframework.http.HttpRequest;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
*
|
||||
* Customize the business tag information obtained from the request
|
||||
*
|
||||
*@author lepdou 2022-05-12
|
||||
*/
|
||||
@Component
|
||||
public class CustomRouterLabelResolver implements RouterLabelResolver {
|
||||
private final Gson gson = new Gson();
|
||||
|
||||
@Override
|
||||
public Map<String, String> resolve(RequestTemplate requestTemplate) {
|
||||
Map<String, String> labels = new HashMap<>();
|
||||
|
||||
User user = gson.fromJson(new String(requestTemplate.body()), User.class);
|
||||
|
||||
labels.put("user", user.getName());
|
||||
|
||||
return labels;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, String> resolve(HttpRequest request, byte[] body) {
|
||||
Map<String, String> labels = new HashMap<>();
|
||||
User user = gson.fromJson(new String(body), User.class);
|
||||
|
||||
labels.put("user", user.getName());
|
||||
return labels;
|
||||
}
|
||||
}
|
@ -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.polaris.router.example;
|
||||
|
||||
/**
|
||||
* demo object.
|
||||
* @author lepdou 2022-05-12
|
||||
*/
|
||||
public class User {
|
||||
|
||||
private String name;
|
||||
private int age;
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(int age) {
|
||||
this.age = age;
|
||||
}
|
||||
}
|
@ -0,0 +1,117 @@
|
||||
/*
|
||||
* 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.context;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import com.tencent.polaris.api.pojo.DefaultServiceEventKeysProvider;
|
||||
import com.tencent.polaris.api.pojo.ServiceEventKey;
|
||||
import com.tencent.polaris.api.pojo.ServiceKey;
|
||||
import com.tencent.polaris.api.pojo.ServiceRule;
|
||||
import com.tencent.polaris.client.api.SDKContext;
|
||||
import com.tencent.polaris.client.flow.BaseFlow;
|
||||
import com.tencent.polaris.client.flow.DefaultFlowControlParam;
|
||||
import com.tencent.polaris.client.flow.FlowControlParam;
|
||||
import com.tencent.polaris.client.flow.ResourcesResponse;
|
||||
import com.tencent.polaris.client.pb.RateLimitProto;
|
||||
import com.tencent.polaris.client.pb.RoutingProto;
|
||||
|
||||
/**
|
||||
* the manager of service governance rules. for example: rate limit rule, router rules.
|
||||
*
|
||||
*@author lepdou 2022-05-13
|
||||
*/
|
||||
public class ServiceRuleManager {
|
||||
|
||||
private final SDKContext sdkContext;
|
||||
|
||||
private final FlowControlParam controlParam;
|
||||
|
||||
public ServiceRuleManager(SDKContext sdkContext) {
|
||||
this.sdkContext = sdkContext;
|
||||
controlParam = new DefaultFlowControlParam();
|
||||
controlParam.setTimeoutMs(sdkContext.getConfig().getGlobal().getAPI().getTimeout());
|
||||
controlParam.setMaxRetry(sdkContext.getConfig().getGlobal().getAPI().getMaxRetryTimes());
|
||||
controlParam.setRetryIntervalMs(sdkContext.getConfig().getGlobal().getAPI().getRetryInterval());
|
||||
}
|
||||
|
||||
public RateLimitProto.RateLimit getServiceRateLimitRule(String namespace, String service) {
|
||||
ServiceEventKey serviceEventKey = new ServiceEventKey(new ServiceKey(namespace, service),
|
||||
ServiceEventKey.EventType.RATE_LIMITING);
|
||||
|
||||
DefaultServiceEventKeysProvider svcKeysProvider = new DefaultServiceEventKeysProvider();
|
||||
svcKeysProvider.setSvcEventKey(serviceEventKey);
|
||||
|
||||
ResourcesResponse resourcesResponse = BaseFlow
|
||||
.syncGetResources(sdkContext.getExtensions(), true, svcKeysProvider, controlParam);
|
||||
|
||||
ServiceRule serviceRule = resourcesResponse.getServiceRule(serviceEventKey);
|
||||
if (serviceRule != null) {
|
||||
Object rule = serviceRule.getRule();
|
||||
if (rule instanceof RateLimitProto.RateLimit) {
|
||||
return (RateLimitProto.RateLimit) rule;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public List<RoutingProto.Route> getServiceRouterRule(String namespace, String sourceService, String dstService) {
|
||||
Set<ServiceEventKey> routerKeys = new HashSet<>();
|
||||
|
||||
ServiceEventKey dstSvcEventKey = new ServiceEventKey(new ServiceKey(namespace, dstService),
|
||||
ServiceEventKey.EventType.ROUTING);
|
||||
routerKeys.add(dstSvcEventKey);
|
||||
|
||||
ServiceEventKey srcSvcEventKey = new ServiceEventKey(new ServiceKey(namespace, sourceService),
|
||||
ServiceEventKey.EventType.ROUTING);
|
||||
|
||||
DefaultServiceEventKeysProvider svcKeysProvider = new DefaultServiceEventKeysProvider();
|
||||
svcKeysProvider.setSvcEventKeys(routerKeys);
|
||||
|
||||
|
||||
ResourcesResponse resourcesResponse = BaseFlow
|
||||
.syncGetResources(sdkContext.getExtensions(), true, svcKeysProvider, controlParam);
|
||||
|
||||
List<RoutingProto.Route> rules = new ArrayList<>();
|
||||
|
||||
//get source service outbound rules.
|
||||
ServiceRule sourceServiceRule = resourcesResponse.getServiceRule(srcSvcEventKey);
|
||||
if (sourceServiceRule != null) {
|
||||
Object rule = sourceServiceRule.getRule();
|
||||
if (rule instanceof RoutingProto.Routing) {
|
||||
rules.addAll(((RoutingProto.Routing) rule).getOutboundsList());
|
||||
}
|
||||
}
|
||||
|
||||
//get peer service inbound rules.
|
||||
ServiceRule dstServiceRule = resourcesResponse.getServiceRule(dstSvcEventKey);
|
||||
if (dstServiceRule != null) {
|
||||
Object rule = dstServiceRule.getRule();
|
||||
if (rule instanceof RoutingProto.Routing) {
|
||||
rules.addAll(((RoutingProto.Routing) rule).getInboundsList());
|
||||
}
|
||||
}
|
||||
|
||||
return rules;
|
||||
}
|
||||
}
|
@ -0,0 +1,58 @@
|
||||
/*
|
||||
* 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.netflix.loadbalancer.Server;
|
||||
import com.tencent.cloud.common.metadata.MetadataContext;
|
||||
import com.tencent.cloud.common.pojo.PolarisServer;
|
||||
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;
|
||||
|
||||
/**
|
||||
* load balancer utils.
|
||||
*
|
||||
*@author lepdou 2022-05-17
|
||||
*/
|
||||
public class LoadBalancerUtils {
|
||||
|
||||
public static ServiceInstances transferServersToServiceInstances(List<Server> servers) {
|
||||
List<Instance> instances = new ArrayList<>(servers.size());
|
||||
String serviceName = null;
|
||||
|
||||
for (Server server : servers) {
|
||||
if (server instanceof PolarisServer) {
|
||||
Instance instance = ((PolarisServer) server).getInstance();
|
||||
instances.add(instance);
|
||||
|
||||
if (serviceName == null) {
|
||||
serviceName = instance.getService();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ServiceKey serviceKey = new ServiceKey(MetadataContext.LOCAL_NAMESPACE, serviceName);
|
||||
|
||||
return new DefaultServiceInstances(serviceKey, instances);
|
||||
}
|
||||
}
|
Loading…
Reference in new issue