Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[type:feat] springcloud plugin dynamic register #5634

Open
wants to merge 50 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 7 commits
Commits
Show all changes
50 commits
Select commit Hold shift + click to select a range
f6e7baa
动态注册中心
WindSearcher Aug 24, 2024
87da45f
Merge remote-tracking branch 'origin/master'
WindSearcher Aug 24, 2024
962ade8
Merge branch 'apache:master' into master
WindSearcher Aug 24, 2024
ea02ebf
fix checkstyle
WindSearcher Aug 25, 2024
4174b5e
Merge remote-tracking branch 'origin/master'
WindSearcher Aug 25, 2024
2aa4ac7
fix e2e
WindSearcher Aug 26, 2024
afb875a
fix checkstyle
WindSearcher Aug 26, 2024
cbbd9f3
Merge branch 'master' into master
Aias00 Aug 29, 2024
86439b2
Merge branch 'master' into master
Aias00 Aug 30, 2024
599d5f7
Merge branch 'master' into master
Aias00 Aug 30, 2024
2cd930b
Merge branch 'master' into master
Aias00 Aug 31, 2024
a09c0a2
Merge branch 'master' into master
Aias00 Aug 31, 2024
e836753
fix ci
WindSearcher Sep 1, 2024
553a790
Merge remote-tracking branch 'origin/master'
WindSearcher Sep 1, 2024
32f9db7
Merge branch 'master' into master
Aias00 Sep 2, 2024
6fa7566
Merge branch 'master' into master
Aias00 Sep 3, 2024
004cf41
Merge branch 'master' into master
Aias00 Sep 3, 2024
4d8f048
Merge branch 'master' into master
Aias00 Sep 4, 2024
f2436de
Merge branch 'master' into master
Aias00 Sep 5, 2024
5ca3f42
Merge branch 'master' into master
Aias00 Sep 5, 2024
cb96aee
fix ci
WindSearcher Sep 6, 2024
3f78cd5
Merge remote-tracking branch 'origin/master'
WindSearcher Sep 6, 2024
1d61d57
fix ci
WindSearcher Sep 6, 2024
ccdf1ae
fix ci
WindSearcher Sep 6, 2024
c7955d7
fix ci
WindSearcher Sep 6, 2024
42099d7
fix ci
WindSearcher Sep 6, 2024
00eb26d
Merge branch 'master' into master
Aias00 Sep 7, 2024
56a95ba
fix ci
WindSearcher Sep 8, 2024
6a72c70
Merge remote-tracking branch 'origin/master'
WindSearcher Sep 8, 2024
03f2deb
fix ci
WindSearcher Sep 8, 2024
1338c3d
fix ci
WindSearcher Sep 8, 2024
50a0ef2
Merge branch 'master' into master
Aias00 Sep 9, 2024
b3449b2
fix ci
WindSearcher Sep 10, 2024
67fbcdd
Merge remote-tracking branch 'origin/master'
WindSearcher Sep 10, 2024
a38aba9
fix ci
WindSearcher Sep 10, 2024
f322d96
Merge branch 'master' into master
Aias00 Sep 13, 2024
79092c3
fix ci
WindSearcher Sep 17, 2024
8b5a210
Merge remote-tracking branch 'origin/master'
WindSearcher Sep 17, 2024
383f57d
fix ci
WindSearcher Sep 17, 2024
9fba108
fix ci
WindSearcher Sep 17, 2024
cc324ae
fix ci
WindSearcher Sep 17, 2024
fe94876
Merge branch 'master' into master
Aias00 Sep 17, 2024
faf60ca
Merge branch 'master' into master
Aias00 Sep 19, 2024
fe63d32
fix ci
WindSearcher Sep 21, 2024
78e76b0
fix ci
WindSearcher Sep 21, 2024
620ae65
fix ci
WindSearcher Sep 21, 2024
2f8e1b9
fix ci
WindSearcher Sep 21, 2024
5117ad9
fix ci
WindSearcher Sep 21, 2024
8482107
fix ci
WindSearcher Sep 21, 2024
0a6e2c6
fix ci
WindSearcher Sep 21, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ public static NamespacePluginRelDO buildPluginNsRelDO(final NamespacePluginDTO n
return Optional.ofNullable(namespacePluginDTO).map(item -> {
Timestamp currentTime = new Timestamp(System.currentTimeMillis());
NamespacePluginRelDO namespacePluginRelDO = NamespacePluginRelDO.builder()
.config(item.getConfig())
.config(item.getConfig() == null ? "" : item.getConfig())
.enabled(item.getEnabled())
.sort(item.getSort())
.namespaceId(item.getNamespaceId())
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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 org.apache.shenyu.common.constant;

/**
* DynamicRegisterConstants.
*/
public class DynamicRegisterConstants {

/**
* The constant REGISTER_TYPE.
*/
public static final String REGISTER_TYPE = "registerType";

public static final String NACOS = "nacos";

public static final String ZOOKEEPER = "zookeeper";

public static final String ETCD = "etcd";

public static final String EUREKA = "eureka";

public static final String SERVER_LISTS = "serverLists";

public static final String NAMESPACE = "namespace";

public static final String USERNAME = "username";

public static final String PASSWORD = "password";

public static final String ACCESS_KEY = "accessKey";

public static final String SECRET_KEY = "secretKey";
}
12 changes: 6 additions & 6 deletions shenyu-examples/shenyu-examples-springcloud/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@

<properties>
<spring-cloud.version>4.1.2</spring-cloud.version>
<nacos-discovery.version>2021.0.1.0</nacos-discovery.version>
<nacos-discovery.version>2022.0.0.0</nacos-discovery.version>
<eureka-client.version>4.1.2</eureka-client.version>
</properties>

Expand Down Expand Up @@ -72,11 +72,11 @@
</exclusions>
</dependency>

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
<version>${eureka-client.version}</version>
</dependency>
<!-- <dependency>-->
<!-- <groupId>org.springframework.cloud</groupId>-->
<!-- <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>-->
<!-- <version>${eureka-client.version}</version>-->
<!-- </dependency>-->

<dependency>
<groupId>org.springframework.boot</groupId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -214,10 +214,10 @@ private <T> void updateCacheData(@NonNull final T data) {
if (data instanceof PluginData) {
PluginData pluginData = (PluginData) data;
final PluginData oldPluginData = BaseDataCache.getInstance().obtainPluginData(pluginData.getName());
BaseDataCache.getInstance().cachePluginData(pluginData);
Optional.ofNullable(handlerMap.get(pluginData.getName()))
.ifPresent(handler -> handler.handlerPlugin(pluginData));

BaseDataCache.getInstance().cachePluginData(pluginData);
// update enabled plugins
PluginHandlerEventEnum state = Boolean.TRUE.equals(pluginData.getEnabled())
? PluginHandlerEventEnum.ENABLED : PluginHandlerEventEnum.DISABLED;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,5 +48,10 @@
<artifactId>shenyu-loadbalancer</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shenyu</groupId>
<artifactId>shenyu-registry-core</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
</project>
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.apache.shenyu.registry.api.entity.InstanceEntity;
import org.springframework.cloud.client.ServiceInstance;

import java.util.Collections;
Expand All @@ -31,15 +32,15 @@
*/
public class ServiceInstanceCache {

private static final Map<String, List<ServiceInstance>> SERVICE_INSTANCE_MAP = Maps.newConcurrentMap();
private static final Map<String, List<InstanceEntity>> SERVICE_INSTANCE_MAP = Maps.newConcurrentMap();

/**
* Cache service instance.
*
* @param serviceId service id
* @param serviceInstances service instance list
*/
public static void cacheServiceInstance(final String serviceId, final List<ServiceInstance> serviceInstances) {
public static void cacheServiceInstance(final String serviceId, final List<InstanceEntity> serviceInstances) {
if (StringUtils.isNotBlank(serviceId)) {
SERVICE_INSTANCE_MAP.put(serviceId, Optional.ofNullable(serviceInstances).orElse(Collections.emptyList()));
}
Expand All @@ -50,7 +51,7 @@ public static void cacheServiceInstance(final String serviceId, final List<Servi
* @param serviceId service id
* @return the list of {@linkplain ServiceInstance}
*/
public static List<ServiceInstance> getServiceInstance(final String serviceId) {
public static List<InstanceEntity> getServiceInstance(final String serviceId) {
if (StringUtils.isBlank(serviceId)) {
return Collections.emptyList();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,10 @@
package org.apache.shenyu.plugin.springcloud.handler;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shenyu.common.config.ShenyuConfig.SpringCloudCacheConfig;
import org.apache.shenyu.common.constant.Constants;
import org.apache.shenyu.common.dto.PluginData;
import org.apache.shenyu.common.dto.RuleData;
import org.apache.shenyu.common.dto.SelectorData;
import org.apache.shenyu.common.dto.convert.rule.impl.SpringCloudRuleHandle;
Expand All @@ -29,13 +31,16 @@
import org.apache.shenyu.common.utils.GsonUtils;
import org.apache.shenyu.loadbalancer.cache.UpstreamCacheManager;
import org.apache.shenyu.loadbalancer.entity.Upstream;
import org.apache.shenyu.plugin.base.cache.BaseDataCache;
import org.apache.shenyu.plugin.base.cache.CommonHandleCache;
import org.apache.shenyu.plugin.base.handler.PluginDataHandler;
import org.apache.shenyu.plugin.base.utils.BeanHolder;
import org.apache.shenyu.plugin.base.utils.CacheKeyUtils;
import org.apache.shenyu.plugin.springcloud.cache.ServiceInstanceCache;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.apache.shenyu.registry.api.ShenyuInstanceRegisterRepository;
import org.apache.shenyu.registry.api.config.RegisterConfig;
import org.apache.shenyu.registry.api.entity.InstanceEntity;
import org.apache.shenyu.registry.core.ShenyuInstanceRegisterRepositoryFactory;

import java.util.List;
import java.util.Optional;
Expand All @@ -50,16 +55,44 @@ public class SpringCloudPluginDataHandler implements PluginDataHandler {
public static final Supplier<CommonHandleCache<String, SpringCloudSelectorHandle>> SELECTOR_CACHED = new BeanHolder<>(CommonHandleCache::new);

public static final Supplier<CommonHandleCache<String, SpringCloudRuleHandle>> RULE_CACHED = new BeanHolder<>(CommonHandleCache::new);
private final DiscoveryClient discoveryClient;

private ShenyuInstanceRegisterRepository repository;

private final SpringCloudCacheConfig springCloudCacheConfig;
public SpringCloudPluginDataHandler(final DiscoveryClient discoveryClient, final SpringCloudCacheConfig springCloudCacheConfig) {
this.discoveryClient = discoveryClient;

public SpringCloudPluginDataHandler(final RegisterConfig config, final SpringCloudCacheConfig springCloudCacheConfig) {
this.repository = ShenyuInstanceRegisterRepositoryFactory.newAndInitInstance(config);
this.springCloudCacheConfig = springCloudCacheConfig;
}


@Override
public void handlerPlugin(final PluginData pluginData) {
if (pluginData == null) {
return;
}
if (!pluginData.getEnabled()) {
return;
}

PluginData oldPluginData = BaseDataCache.getInstance().obtainPluginData(pluginData.getName());
String newConfig = pluginData.getConfig();
String oldConfig = oldPluginData != null ? oldPluginData.getConfig() : "";
RegisterConfig newRegisterConfig = GsonUtils.getInstance().fromJson(newConfig, RegisterConfig.class);
if (newRegisterConfig == null) {
return;
}
RegisterConfig oldRegisterConfig = null;
if (StringUtils.isNotBlank(oldConfig)) {
oldRegisterConfig = GsonUtils.getInstance().fromJson(oldConfig, RegisterConfig.class);
}

if (!newRegisterConfig.equals(oldRegisterConfig)) {
RegisterConfig refreshRegisterConfig = GsonUtils.getInstance().fromJson(newConfig, RegisterConfig.class);
this.repository.close();
this.repository = ShenyuInstanceRegisterRepositoryFactory.reNewAndInitInstance(refreshRegisterConfig);
}
}

@Override
public void handlerSelector(final SelectorData selectorData) {
SpringCloudSelectorHandle springCloudSelectorHandle = GsonUtils.getInstance().fromJson(selectorData.getHandle(), SpringCloudSelectorHandle.class);
Expand All @@ -69,7 +102,7 @@ public void handlerSelector(final SelectorData selectorData) {
return;
}
if (springCloudCacheConfig.getEnabled()) {
List<ServiceInstance> serviceInstances = discoveryClient.getInstances(springCloudSelectorHandle.getServiceId());
List<InstanceEntity> serviceInstances = repository.selectInstances(springCloudSelectorHandle.getServiceId());
ServiceInstanceCache.cacheServiceInstance(springCloudSelectorHandle.getServiceId(), serviceInstances);
}
UpstreamCacheManager.getInstance().submit(selectorData.getId(), convertUpstreamList(springCloudSelectorHandle.getDivideUpstreams()));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,14 @@
import org.apache.shenyu.common.dto.convert.selector.SpringCloudSelectorHandle;
import org.apache.shenyu.common.utils.LogUtils;
import org.apache.shenyu.plugin.springcloud.cache.ServiceInstanceCache;

import static org.apache.shenyu.plugin.springcloud.handler.SpringCloudPluginDataHandler.SELECTOR_CACHED;
import org.apache.shenyu.registry.api.ShenyuInstanceRegisterRepository;
import org.apache.shenyu.registry.api.config.RegisterConfig;
import org.apache.shenyu.registry.api.entity.InstanceEntity;
import org.apache.shenyu.registry.core.ShenyuInstanceRegisterRepositoryFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.discovery.event.HeartbeatEvent;
import org.springframework.context.ApplicationListener;

Expand All @@ -39,13 +42,13 @@
public class SpringCloudHeartBeatListener implements ApplicationListener<HeartbeatEvent> {

private static final Logger LOG = LoggerFactory.getLogger(SpringCloudHeartBeatListener.class);
private final DiscoveryClient discoveryClient;

private final ShenyuInstanceRegisterRepository repository;

private final SpringCloudCacheConfig cacheConfig;
public SpringCloudHeartBeatListener(final DiscoveryClient discoveryClient, final SpringCloudCacheConfig cacheConfig) {
this.discoveryClient = discoveryClient;

public SpringCloudHeartBeatListener(final RegisterConfig config, final SpringCloudCacheConfig cacheConfig) {
this.repository = ShenyuInstanceRegisterRepositoryFactory.newAndInitInstance(config);
this.cacheConfig = cacheConfig;
}

Expand All @@ -61,7 +64,7 @@ public void onApplicationEvent(final HeartbeatEvent event) {
}
map.forEach((key, value) -> {
String serviceId = value.getServiceId();
List<ServiceInstance> serviceInstanceList = discoveryClient.getInstances(serviceId);
List<InstanceEntity> serviceInstanceList = repository.selectInstances(serviceId);
ServiceInstanceCache.cacheServiceInstance(serviceId, serviceInstanceList);
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,13 @@
import org.apache.shenyu.loadbalancer.factory.LoadBalancerFactory;
import org.apache.shenyu.plugin.springcloud.cache.ServiceInstanceCache;
import org.apache.shenyu.plugin.springcloud.handler.SpringCloudPluginDataHandler;
import org.apache.shenyu.registry.api.ShenyuInstanceRegisterRepository;
import org.apache.shenyu.registry.api.config.RegisterConfig;
import org.apache.shenyu.registry.api.entity.InstanceEntity;
import org.apache.shenyu.registry.core.ShenyuInstanceRegisterRepositoryFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;

import java.util.ArrayList;
import java.util.Collections;
Expand All @@ -45,10 +48,10 @@ public final class ShenyuSpringCloudServiceChooser {

private static final Logger LOG = LoggerFactory.getLogger(ShenyuSpringCloudServiceChooser.class);

private final DiscoveryClient discoveryClient;
private ShenyuInstanceRegisterRepository repository;

public ShenyuSpringCloudServiceChooser(final DiscoveryClient discoveryClient) {
this.discoveryClient = discoveryClient;
public ShenyuSpringCloudServiceChooser(final RegisterConfig config) {
this.repository = ShenyuInstanceRegisterRepositoryFactory.newAndInitInstance(config);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It should not be initialized here. You need to consider getting the latest instance in the method after modification.

}

/**
Expand All @@ -63,7 +66,7 @@ public ShenyuSpringCloudServiceChooser(final DiscoveryClient discoveryClient) {
public Upstream choose(final String serviceId, final String selectorId,
final String ip, final String loadbalancer) {
// load service instance by serviceId
List<ServiceInstance> available = this.getServiceInstance(serviceId);
List<InstanceEntity> available = this.getServiceInstance(serviceId);
if (CollectionUtils.isEmpty(available)) {
LOG.info("choose return 1");
return null;
Expand All @@ -81,7 +84,7 @@ public Upstream choose(final String serviceId, final String selectorId,
}
// select server from available to choose
final List<Upstream> choose = new ArrayList<>(available.size());
for (ServiceInstance serviceInstance : available) {
for (InstanceEntity serviceInstance : available) {
divideUpstreams.stream()
.filter(Upstream::isStatus)
.filter(upstream -> Objects.equals(upstream.getUrl(), serviceInstance.getUri().getRawAuthority()))
Expand Down Expand Up @@ -121,9 +124,9 @@ private Upstream doSelect(final List<Upstream> upstreamList, final String loadba
* @param serviceId serviceId
* @return {@linkplain ServiceInstance}
*/
private List<ServiceInstance> getServiceInstance(final String serviceId) {
private List<InstanceEntity> getServiceInstance(final String serviceId) {
if (CollectionUtils.isEmpty(ServiceInstanceCache.getServiceInstance(serviceId))) {
List<ServiceInstance> instances = discoveryClient.getInstances(serviceId);
List<InstanceEntity> instances = repository.selectInstances(serviceId);
LOG.info("getServiceInstance: {}", JsonUtils.toJson(instances));
return Optional.ofNullable(instances).orElse(Collections.emptyList());
}
Expand All @@ -138,7 +141,7 @@ private List<ServiceInstance> getServiceInstance(final String serviceId) {
* @return Upstream List
*/
private List<Upstream> buildUpstream(final String serviceId) {
List<ServiceInstance> serviceInstanceList = this.getServiceInstance(serviceId);
List<InstanceEntity> serviceInstanceList = this.getServiceInstance(serviceId);
if (CollectionUtils.isEmpty(serviceInstanceList)) {
return Collections.emptyList();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@
import org.apache.shenyu.plugin.api.utils.WebFluxResultUtils;
import org.apache.shenyu.plugin.base.utils.CacheKeyUtils;
import org.apache.shenyu.plugin.springcloud.handler.SpringCloudPluginDataHandler;
import org.apache.shenyu.plugin.springcloud.loadbalance.ShenyuSpringCloudServiceChooser;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
Expand All @@ -44,8 +43,6 @@
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import org.springframework.cloud.client.DefaultServiceInstance;
import org.springframework.cloud.client.discovery.simple.SimpleDiscoveryClient;
import org.springframework.cloud.client.discovery.simple.SimpleDiscoveryProperties;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.http.HttpMethod;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
Expand All @@ -60,9 +57,7 @@
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

Expand Down Expand Up @@ -112,13 +107,13 @@ public void setUp() {
defaultServiceInstance.setPort(8080);
defaultServiceInstance.setHost("localhost");
serviceInstanceList.add(defaultServiceInstance);
SimpleDiscoveryProperties simpleDiscoveryProperties = new SimpleDiscoveryProperties();
Map<String, List<DefaultServiceInstance>> serviceInstanceMap = new HashMap<>();
serviceInstanceMap.put(defaultServiceInstance.getInstanceId(), serviceInstanceList);
simpleDiscoveryProperties.setInstances(serviceInstanceMap);
SimpleDiscoveryClient discoveryClient = new SimpleDiscoveryClient(simpleDiscoveryProperties);
ShenyuSpringCloudServiceChooser loadBalancerClient = new ShenyuSpringCloudServiceChooser(discoveryClient);
springCloudPlugin = new SpringCloudPlugin(loadBalancerClient);
// SimpleDiscoveryProperties simpleDiscoveryProperties = new SimpleDiscoveryProperties();
// Map<String, List<DefaultServiceInstance>> serviceInstanceMap = new HashMap<>();
// serviceInstanceMap.put(defaultServiceInstance.getInstanceId(), serviceInstanceList);
// simpleDiscoveryProperties.setInstances(serviceInstanceMap);
// SimpleDiscoveryClient discoveryClient = new SimpleDiscoveryClient(simpleDiscoveryProperties);
// ShenyuSpringCloudServiceChooser loadBalancerClient = new ShenyuSpringCloudServiceChooser(discoveryClient);
// springCloudPlugin = new SpringCloudPlugin(loadBalancerClient);
}

@Test
Expand Down
Loading
Loading