TODO: ConfigApollo Created In Bean.

This commit is contained in:
huangsimin 2019-08-13 18:28:05 +08:00
parent 9734ee1826
commit ce404ecf6b
8 changed files with 151 additions and 59 deletions

View File

@ -18,7 +18,7 @@
<description>Demo project for Yame User Gateway</description>
<properties>
<java.version>1.11</java.version>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-cloud.version>Greenwich.SR2</spring-cloud.version>

View File

@ -16,7 +16,7 @@
<description>Demo project for Gateway Service</description>
<properties>
<java.version>1.11</java.version>
<java.version>1.8</java.version>
</properties>
<dependencies>

View File

@ -1,7 +1,5 @@
package cn.ecpark.service.usergw;
import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig;
import org.apache.dubbo.config.spring.context.annotation.EnableDubboConfig;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.boot.SpringApplication;
@ -20,7 +18,6 @@ import org.springframework.context.annotation.Configuration;
@EnableAutoConfiguration
@EnableDubboConfig
@ComponentScan("cn.ecpark.service.usergw")
@EnableApolloConfig
public class App {
public static void main(String[] args) {

View File

@ -0,0 +1,23 @@
package cn.ecpark.service.usergw.biz.events;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Service;
@Service
public class Change implements ApplicationEventPublisherAware {
private ApplicationEventPublisher publisher;
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.publisher = applicationEventPublisher;
}
public void notifyChanged() {
this.publisher.publishEvent(new RefreshRoutesEvent(this));
}
}

View File

@ -3,6 +3,7 @@ package cn.ecpark.service.usergw.config;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.cloud.gateway.route.RouteDefinitionWriter;
import org.springframework.context.ApplicationEventPublisher;
@ -11,30 +12,47 @@ import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigService;
import com.ctrip.framework.apollo.model.ConfigChange;
import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfig;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;
import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig;
@Slf4j
@Configurable
@Service
@EnableApolloConfig
public class ConfigApollo implements ApplicationEventPublisherAware {
private ApplicationEventPublisher publisher;
public void notifyChanged() {
this.publisher.publishEvent(new RefreshRoutesEvent(this));
// @EnableApolloConfig("gateway.yml")
// @ConditionalOnProperty(prefix="app", value="id", matchIfMissing=true)
// @Configurable
public class ConfigApollo {
// private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(ConfigApollo.class);
// @ApolloConfig("gateway.yml")
private Config config;
public ConfigApollo() {
}
@ApolloConfigChangeListener("gateway.yml")
// @ApolloConfigChangeListener("gateway.yml")
private void listenApolloChange(ConfigChangeEvent changeEvent) {
log.warn(changeEvent.getNamespace());
}
/**
* @return Config return the config
*/
public Config getConfig() {
return config;
}
/**
* @param config the config to set
*/
public void setConfig(Config config) {
this.config = config;
}
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.publisher = applicationEventPublisher;
}
}

View File

@ -1,6 +1,8 @@
package cn.ecpark.service.usergw.config;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
@ -12,6 +14,11 @@ import java.util.Map.Entry;
import java.util.Set;
import java.util.function.BiConsumer;
import com.ctrip.framework.apollo.internals.ConfigRepository;
import com.ctrip.framework.apollo.internals.DefaultConfig;
import com.ctrip.framework.apollo.internals.PropertiesCompatibleFileConfigRepository;
import com.ctrip.framework.apollo.internals.YmlConfigFile;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.rpc.service.GenericService;
import org.springframework.beans.factory.annotation.Autowired;
@ -27,21 +34,26 @@ import org.yaml.snakeyaml.Yaml;
import cn.ecpark.service.usergw.biz.filters.bean.GenericServicePool;
import cn.ecpark.service.usergw.utils.Extract;
import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Flux;
/**
* ConfigGateway
*/
@Component
@Slf4j
public class ConfigGateway implements RouteDefinitionLocator {
// List<MediaType> mediaTypes = new ArrayList<>();
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(ConfigGateway.class);
@Value("${yame.config}")
@Value("${yame.config:}")
private String yameConfigPath;
@Value("${apollo.meta:}")
private String apolloMeta;
@Value("${app.id:}")
private String appID;
private List<FilterDefinition> defaultFilters = new ArrayList<>();
private HashMap<String, BiConsumer<ReferenceConfig<GenericService>, Object>> specialField = new HashMap<String, BiConsumer<ReferenceConfig<GenericService>, Object>>();
private Set<String> ignoreKey = new HashSet<>();
@ -67,7 +79,7 @@ public class ConfigGateway implements RouteDefinitionLocator {
private InputStream loadLocalFileConfig() {
Object inputStream = null;
String[] gatewayConfigPathList;
if (yameConfigPath == null) {
if (yameConfigPath.equals("")) {
gatewayConfigPathList = new String[] { "gateway.yml", "gateway.yaml", "Gateway.yml", "Gateway.yaml" };
} else {
gatewayConfigPathList = new String[] { yameConfigPath };
@ -79,20 +91,47 @@ public class ConfigGateway implements RouteDefinitionLocator {
break;
}
}
return (InputStream)inputStream;
return (InputStream) inputStream;
}
private InputStream loadApolloConfige() {
private InputStream loadApolloConfig() {
if (true) return null;
ConfigApollo configApollo = appContext.getBean(ConfigApollo.class);
DefaultConfig config = (DefaultConfig) configApollo.getConfig();
try {
Field m_configRepository = DefaultConfig.class.getDeclaredField("m_configRepository");
m_configRepository.setAccessible(true);
ConfigRepository cr = (ConfigRepository) m_configRepository.get(config);
Field configFile = PropertiesCompatibleFileConfigRepository.class.getDeclaredField("configFile");
configFile.setAccessible(true);
YmlConfigFile ymlConfigFile = (YmlConfigFile) configFile.get(cr);
String content = ymlConfigFile.getContent();
log.info("Load Apollo YAML Config: \n{}", content);
return new ByteArrayInputStream(content.getBytes());
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
@Override
@SuppressWarnings("unchecked")
public Flux<RouteDefinition> getRouteDefinitions() {
// WebFluxConfigurationSupport a;
defaultFilters.clear();
InputStream inputStream = loadLocalFileConfig();
InputStream inputStream;
if(!this.apolloMeta.equals("") && !this.appID.equals("")) {
inputStream = loadApolloConfig();
} else {
inputStream = loadLocalFileConfig();
}
if (inputStream != null) {
Map<String, Object> configYaml = new Yaml().load(inputStream);
if (configYaml != null) {
@ -100,7 +139,7 @@ public class ConfigGateway implements RouteDefinitionLocator {
List<String> defaultFiltersYaml = null;
Map<String, Object> restfulYaml = null;
Map<String, Object> dubboYaml = null;
Object unknown;
unknown = configYaml.get("default-filters");
if (unknown != null) {
@ -264,7 +303,7 @@ public class ConfigGateway implements RouteDefinitionLocator {
/**
*
* @param rd {@link RouteDefinition}
* @param rd {@link RouteDefinition}
* @param iter Yaml.dubbo.routes
* @return dubboUri 字符串标识 eg. dubbo://application/group/com.a.b:1.0.0
*/
@ -294,12 +333,11 @@ public class ConfigGateway implements RouteDefinitionLocator {
// 设置uri
Object order = iter.get("order");
if (order != null) {
rd.setOrder((int)order);
rd.setOrder((int) order);
iter.remove("order");
} else {
rd.setOrder(0);
}
ReferenceConfig<GenericService> reference = new ReferenceConfig<GenericService>();
reference.setConnections(3);
@ -358,9 +396,9 @@ public class ConfigGateway implements RouteDefinitionLocator {
/**
*
* @param predicates List<{@link PredicateDefinition}> 断言列表
* @param iter restful.routes.predicates
* @param yamlField 根据域的key 获取 predicates 字符串列
* @param predicates List<{@link PredicateDefinition}> 断言列表
* @param iter restful.routes.predicates
* @param yamlField 根据域的key 获取 predicates 字符串列
*/
private void parseAndAddPredicates(List<PredicateDefinition> predicates, LinkedHashMap<String, List<String>> iter,
String yamlField) {
@ -374,9 +412,9 @@ public class ConfigGateway implements RouteDefinitionLocator {
/**
*
* @param filters List<{@link FilterDefinition}> 过滤器列表
* @param iter restful.routes.filters
* @param yamlField 根据域的key 获取 filters 字符串列
* @param filters List<{@link FilterDefinition}> 过滤器列表
* @param iter restful.routes.filters
* @param yamlField 根据域的key 获取 filters 字符串列
*/
private void parseAndAddFilters(List<FilterDefinition> filters, LinkedHashMap<String, List<String>> iter,
String yamlField) {
@ -391,43 +429,44 @@ public class ConfigGateway implements RouteDefinitionLocator {
/**
*
* @param dubboUri 获取返回的字符串 {@link #parseDubboUriAndSetBase(RouteDefinition, LinkedHashMap)}
* @param filters List<{@link FilterDefinition}> 过滤器列表
* @param iter dubbo.routes.filters
* @param dubboUri 获取返回的字符串
* {@link #parseDubboUriAndSetBase(RouteDefinition, LinkedHashMap)}
* @param filters List<{@link FilterDefinition}> 过滤器列表
* @param iter dubbo.routes.filters
* @param yamlField 根据域的key 获取 filters 字符串列
*/
@SuppressWarnings("unchecked")
private void parseAndAddDubboFilters(String dubboUri, List<FilterDefinition> filters,
LinkedHashMap<String, List<String>> iter, String yamlField) {
List<String> filtersYaml = iter.get(yamlField);
filters.addAll(defaultFilters);
if (filtersYaml != null) {
for (Object filterObject : filtersYaml) {
// 现阶段只支持两种情况
if(filterObject.getClass() == String.class) {
String filterString = (String)filterObject;
if (filterObject.getClass() == String.class) {
String filterString = (String) filterObject;
FilterDefinition fd = new FilterDefinition(filterString);
log.info(fd.getName());
if (!fd.getName().equals("Dubbo")) {
filters.add(fd);
}
} else if (filterObject.getClass() == LinkedHashMap.class) {
Map<String, Object> filterMap = (LinkedHashMap<String, Object>)filterObject;
Map<String, Object> filterMap = (LinkedHashMap<String, Object>) filterObject;
FilterDefinition fd = new FilterDefinition();
fd.setName((String)filterMap.get("name"));
if(filterMap.containsKey("args")) {
fd.setName((String) filterMap.get("name"));
if (filterMap.containsKey("args")) {
Object args = filterMap.get("args");
for( Entry<String, Object> kv : ((Map<String, Object>)args).entrySet()) {
if(kv.getValue().getClass() != String.class) {
kv.setValue( String.valueOf(kv.getValue()));
for (Entry<String, Object> kv : ((Map<String, Object>) args).entrySet()) {
if (kv.getValue().getClass() != String.class) {
kv.setValue(String.valueOf(kv.getValue()));
}
}
fd.setArgs((Map<String,String>)args);
fd.setArgs((Map<String, String>) args);
}
log.info(fd.getName());
if (!fd.getName().equals("Dubbo")) {
filters.add(fd);

View File

@ -6,6 +6,7 @@ import org.springframework.stereotype.Component;
import cn.ecpark.service.usergw.biz.filters.bean.GenericServicePool;
import cn.ecpark.service.usergw.biz.filters.factory.DubboGatewayFilterFactory;
import cn.ecpark.service.usergw.config.ConfigApollo;
import reactor.core.publisher.Mono;
@Component
@ -24,4 +25,11 @@ public class ConfigBean {
KeyResolver ipResolver() {
return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getHostString());
}
@Bean
ConfigApollo configApollo() {
ConfigApollo ca = new ConfigApollo();
return ca;
}
}

View File

@ -1,8 +1,16 @@
spring.application.name=gateway
app.id=gateway
apollo.meta=http://127.0.0.1:8180
# app.id=gateway
# apollo.meta=http://localhost:8180
# local.meta=http://localhost:8180
# dev.meta=http://localhost:8180
# fat.meta=http://localhost:8180
# uat.meta=http://localhost:8180
# lpt.meta=http://localhost:8180
# pro.meta=http://localhost:8180
# eureka.instance.ip-address=http://localhost:8180
dubbo.scan.base-packages=cn.ecpark.service.usergw.impl
dubbo.protocol.name=dubbo
@ -14,7 +22,6 @@ server.port=8888
# logging.level.org.springframework.cloud.gateway=debug
logging.file=logs/log
yame.config=gateway.yaml