update Nacos by using the Spring cloud version (#225)

This commit is contained in:
zhong-jie
2021-06-08 14:29:27 +08:00
committed by GitHub
parent edc0df6db3
commit 3282bae017
41 changed files with 654 additions and 326 deletions

View File

@@ -16,7 +16,6 @@
*/ */
package we; package we;
import com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
@@ -180,7 +179,6 @@ import we.log.LogSendAppender;
QuartzAutoConfiguration.class QuartzAutoConfiguration.class
} }
) )
@NacosPropertySource(dataId = "${nacos.config.data-id}", groupId = "${nacos.config.group}", autoRefreshed = true)
@EnableDiscoveryClient @EnableDiscoveryClient
public class FizzBootstrapApplication { public class FizzBootstrapApplication {
private static final Logger LOGGER = LoggerFactory.getLogger(FizzBootstrapApplication.class); private static final Logger LOGGER = LoggerFactory.getLogger(FizzBootstrapApplication.class);

View File

@@ -12,30 +12,6 @@ apollo:
enabled: false #use Apollo? enabled: false #use Apollo?
################################################### Apollo config end ################################################### ################################################### Apollo config end ###################################################
# if you do not use Nacos, ignore the follow config
################################################## Nacos config start ###################################################
nacos:
config:
# if use Nacos config set this flag to true
enabled: false #use Nacos Config? (default:false)
# need replace
server-addr: localhost:8848 #please input the nacos config server-addr (default:localhost:8848)
auto-refresh: true
group: fizz-gateway #please input the nacos config group (default:fizz-gateway)
data-id: application #please input the nacos config data-id (default:application)
type: PROPERTIES #please input the nacos config type (default:PROPERTIES)
# need replace
namespace: null #please input the nacos config type (default:null)
discovery:
# if use Nacos discovery set this flag to true
enabled: false #use Nacos Discovery? (default:false)
# need replace
server-addr: localhost:8848 #please input the nacos discovery server-addr (default:localhost:8848)
auto-register: true
register:
group-name: fizz-gateway #please input the nacos discovery register group-name (default:fizz-gateway)
################################################### Nacos config end ####################################################
# if you do not use Eureka, ignore the follow config # if you do not use Eureka, ignore the follow config
################################################## Eureka config start ################################################## ################################################## Eureka config start ##################################################
eureka: eureka:
@@ -62,6 +38,14 @@ spring:
loadbalancer: loadbalancer:
ribbon: ribbon:
enabled: false enabled: false
nacos:
discovery:
# if use Nacos discovery set this flag to true
enabled: false #use Nacos Discovery? (default:false)
# need replace
server-addr: localhost:8848 #please input the nacos discovery server-addr (default:localhost:8848)
namespace: null #please input the nacos config type (default:null)
group: fizz-gateway #please input the nacos discovery register group (default:fizz-gateway)
aggregate: aggregate:
redis: redis:

View File

@@ -0,0 +1,15 @@
spring:
cloud:
nacos:
config:
# if use Nacos config set this flag to true
enabled: false #use Nacos Config? (default:false)
# need replace
server-addr: localhost:8848 #please input the nacos config server-addr (default:localhost:8848)
namespace: null #please input the nacos config type (default:null)
group: fizz-gateway #please input the nacos config group (default:fizz-gateway)
prefix: application #please input the nacos config data-id (default:application)
extension-configs[0]:
refresh: true
data-id: ${spring.cloud.nacos.config.prefix}
group: ${spring.cloud.nacos.config.group}

View File

@@ -17,6 +17,8 @@
<AppenderRef ref="Console" /> <AppenderRef ref="Console" />
<AppenderRef ref="LogSend" /> <AppenderRef ref="LogSend" />
</Root> </Root>
<!-- suppress the warn 'No URLs will be polled as dynamic configuration sources.' -->
<logger name="com.netflix.config.sources.URLConfigurationSource" level="ERROR"/>
<Logger name="we" level="warn" additivity="false" /> <Logger name="we" level="warn" additivity="false" />
</Loggers> </Loggers>
</Configuration> </Configuration>

View File

@@ -136,19 +136,13 @@
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.alibaba.boot</groupId> <groupId>com.alibaba.cloud</groupId>
<artifactId>nacos-config-spring-boot-starter</artifactId> <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.alibaba.boot</groupId> <groupId>com.alibaba.cloud</groupId>
<artifactId>nacos-discovery-spring-boot-starter</artifactId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency> </dependency>
<dependency> <dependency>
@@ -156,6 +150,11 @@
<artifactId>commons-pool2</artifactId> <artifactId>commons-pool2</artifactId>
</dependency> </dependency>
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis-reactive</artifactId> <artifactId>spring-boot-starter-data-redis-reactive</artifactId>

View File

@@ -17,9 +17,7 @@
package we.config; package we.config;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
@@ -40,10 +38,11 @@ import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSeriali
import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.session.data.redis.config.annotation.SpringSessionRedisConnectionFactory; import org.springframework.session.data.redis.config.annotation.SpringSessionRedisConnectionFactory;
import we.log.LogSendAppender; import we.log.LogSendAppender;
import we.log.RedisLogSendServiceImpl; import we.log.RedisLogSendServiceImpl;
import javax.annotation.Resource;
/** /**
* aggregate Redis config * aggregate Redis config
* *
@@ -59,17 +58,8 @@ public class AggregateRedisConfig extends RedisReactiveConfig {
private static final String SEND_LOG_TYPE_REDIS = "redis"; private static final String SEND_LOG_TYPE_REDIS = "redis";
public static ProxyLettuceConnectionFactory proxyLettuceConnectionFactory; public static ProxyLettuceConnectionFactory proxyLettuceConnectionFactory;
@NacosValue(value = "${send-log.open:false}", autoRefreshed = true) @Resource
@Value("${send-log.open:false}") private AggregateRedisConfigProperties aggregateRedisConfigProperties;
private boolean sendLogOpen;
@NacosValue(value = "${send-log.channel:fizz_send_log_channel}", autoRefreshed = true)
@Value("${send-log.channel:fizz_log_channel}")
private String sendLogChannel;
@NacosValue(value = "${send-log.type:redis}", autoRefreshed = true)
@Value("${send-log.type:redis}")
private String sendLogType;
@ConfigurationProperties(prefix = "aggregate.redis") @ConfigurationProperties(prefix = "aggregate.redis")
@Configuration(AGGREGATE_REACTIVE_REDIS_PROPERTIES) @Configuration(AGGREGATE_REACTIVE_REDIS_PROPERTIES)
@@ -84,7 +74,7 @@ public class AggregateRedisConfig extends RedisReactiveConfig {
@Bean(AGGREGATE_REACTIVE_REDIS_CONNECTION_FACTORY) @Bean(AGGREGATE_REACTIVE_REDIS_CONNECTION_FACTORY)
public ReactiveRedisConnectionFactory lettuceConnectionFactory() { public ReactiveRedisConnectionFactory lettuceConnectionFactory() {
LettuceConnectionFactory lettuceConnectionFactory = (LettuceConnectionFactory) super.lettuceConnectionFactory(); LettuceConnectionFactory lettuceConnectionFactory = (LettuceConnectionFactory) super.lettuceConnectionFactory();
if (SEND_LOG_TYPE_REDIS.equals(sendLogType)) { if (SEND_LOG_TYPE_REDIS.equals(aggregateRedisConfigProperties.getSendLogType())) {
proxyLettuceConnectionFactory = new ProxyLettuceConnectionFactory(lettuceConnectionFactory); proxyLettuceConnectionFactory = new ProxyLettuceConnectionFactory(lettuceConnectionFactory);
proxyLettuceConnectionFactory.afterPropertiesSet(); proxyLettuceConnectionFactory.afterPropertiesSet();
return proxyLettuceConnectionFactory; return proxyLettuceConnectionFactory;
@@ -102,9 +92,10 @@ public class AggregateRedisConfig extends RedisReactiveConfig {
// test redis can connect // test redis can connect
reactiveStringRedisTemplate.getConnectionFactory().getReactiveConnection().ping().block(); reactiveStringRedisTemplate.getConnectionFactory().getReactiveConnection().ping().block();
if (SEND_LOG_TYPE_REDIS.equals(sendLogType)) { if (SEND_LOG_TYPE_REDIS.equals(aggregateRedisConfigProperties.getSendLogType())) {
// set LogSendAppender.logSendService here to let send log as early as possible // set LogSendAppender.logSendService here to let send log as early as possible
LogSendAppender.logSendService = new RedisLogSendServiceImpl(this, reactiveStringRedisTemplate); LogSendAppender.logSendService = new RedisLogSendServiceImpl(aggregateRedisConfigProperties, this,
reactiveStringRedisTemplate);
} }
return reactiveStringRedisTemplate; return reactiveStringRedisTemplate;
@@ -149,14 +140,6 @@ public class AggregateRedisConfig extends RedisReactiveConfig {
template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer()); template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
return template; return template;
} }
public boolean getSendLogOpen() {
return sendLogOpen;
}
public String getSendLogChannel() {
return sendLogChannel;
}
public static class ProxyLettuceConnectionFactory implements RedisConnectionFactory, ReactiveRedisConnectionFactory { public static class ProxyLettuceConnectionFactory implements RedisConnectionFactory, ReactiveRedisConnectionFactory {
ProxyLettuceConnectionFactory(LettuceConnectionFactory lettuceConnectionFactory) { ProxyLettuceConnectionFactory(LettuceConnectionFactory lettuceConnectionFactory) {

View File

@@ -0,0 +1,43 @@
/*
* Copyright (C) 2020 the original author or authors.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package we.config;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
/**
* {@link AggregateRedisConfig} properties
*
* @author zhongjie
*/
@RefreshScope
@Component
@Data
public class AggregateRedisConfigProperties {
@Value("${send-log.open:false}")
private boolean sendLogOpen;
@Value("${send-log.channel:fizz_log_channel}")
private String sendLogChannel;
@Value("${send-log.type:redis}")
private String sendLogType;
}

View File

@@ -17,27 +17,20 @@
package we.config; package we.config;
import com.alibaba.nacos.api.config.annotation.NacosValue; import lombok.Data;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration; import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
/** /**
* @author unknown * @author unknown
*/ */
@RefreshScope
@Configuration @Component
@Data
public class AppConfigProperties { public class AppConfigProperties {
@NacosValue(value = "${spring.profiles.active}", autoRefreshed = true)
@Value("${spring.profiles.active}") @Value("${spring.profiles.active}")
private String env; private String env;
public String getEnv() {
return env;
}
public void setEnv(String env) {
this.env = env;
}
} }

View File

@@ -17,11 +17,9 @@
package we.config; package we.config;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.ReactiveStringRedisTemplate; import org.springframework.data.redis.core.ReactiveStringRedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.EnableScheduling;
@@ -70,9 +68,8 @@ public class FlowStatSchedConfig extends SchedConfig {
private static final String _minRespTime = "\"minRespTime\":"; private static final String _minRespTime = "\"minRespTime\":";
private static final String _maxRespTime = "\"maxRespTime\":"; private static final String _maxRespTime = "\"maxRespTime\":";
@NacosValue(value = "${flowControl:false}", autoRefreshed = true) @Resource
@Value("${flowControl:false}") private FlowStatSchedConfigProperties flowStatSchedConfigProperties;
private boolean flowControl;
// @Resource // @Resource
@Autowired(required = false) @Autowired(required = false)
@@ -81,14 +78,6 @@ public class FlowStatSchedConfig extends SchedConfig {
@Resource @Resource
private ResourceRateLimitConfigService resourceRateLimitConfigService; private ResourceRateLimitConfigService resourceRateLimitConfigService;
@NacosValue(value = "${flow-stat-sched.dest:redis}", autoRefreshed = true)
@Value("${flow-stat-sched.dest:redis}")
private String dest;
@NacosValue(value = "${flow-stat-sched.queue:fizz_resource_access_stat}", autoRefreshed = true)
@Value("${flow-stat-sched.queue:fizz_resource_access_stat}")
private String queue;
@Resource(name = AggregateRedisConfig.AGGREGATE_REACTIVE_REDIS_TEMPLATE) @Resource(name = AggregateRedisConfig.AGGREGATE_REACTIVE_REDIS_TEMPLATE)
private ReactiveStringRedisTemplate rt; private ReactiveStringRedisTemplate rt;
@@ -101,7 +90,7 @@ public class FlowStatSchedConfig extends SchedConfig {
@Scheduled(cron = "${flow-stat-sched.cron}") @Scheduled(cron = "${flow-stat-sched.cron}")
public void sched() { public void sched() {
if (!flowControl) { if (!flowStatSchedConfigProperties.isFlowControl()) {
return; return;
} }
if (startTimeSlot == 0) { if (startTimeSlot == 0) {
@@ -173,10 +162,10 @@ public class FlowStatSchedConfig extends SchedConfig {
b.append(_minRespTime); b.append(w.getMin()); b.append(_minRespTime); b.append(w.getMin());
b.append(Constants.Symbol.RIGHT_BRACE); b.append(Constants.Symbol.RIGHT_BRACE);
String msg = b.toString(); String msg = b.toString();
if ("kafka".equals(dest)) { // for internal use if ("kafka".equals(flowStatSchedConfigProperties.getDest())) { // for internal use
log.warn(msg, LogService.HANDLE_STGY, LogService.toKF(queue)); log.warn(msg, LogService.HANDLE_STGY, LogService.toKF(flowStatSchedConfigProperties.getQueue()));
} else { } else {
rt.convertAndSend(queue, msg).subscribe(); rt.convertAndSend(flowStatSchedConfigProperties.getQueue(), msg).subscribe();
} }
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("report " + toDP19(winStart) + " win10: " + msg); log.debug("report " + toDP19(winStart) + " win10: " + msg);

View File

@@ -0,0 +1,42 @@
/*
* Copyright (C) 2020 the original author or authors.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package we.config;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
/**
* {@link FlowStatSchedConfig} properties
*
* @author zhongjie
*/
@RefreshScope
@Component
@Data
public class FlowStatSchedConfigProperties {
@Value("${flowControl:false}")
private boolean flowControl;
@Value("${flow-stat-sched.dest:redis}")
private String dest;
@Value("${flow-stat-sched.queue:fizz_resource_access_stat}")
private String queue;
}

View File

@@ -16,10 +16,8 @@
*/ */
package we.config; package we.config;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.annotation.Scheduled;
import we.fizz.ConfigLoader; import we.fizz.ConfigLoader;
@@ -48,27 +46,8 @@ import javax.annotation.Resource;
public class RefreshLocalCacheConfig { public class RefreshLocalCacheConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(RefreshLocalCacheConfig.class); private static final Logger LOGGER = LoggerFactory.getLogger(RefreshLocalCacheConfig.class);
@NacosValue(value = "${refresh-local-cache.api-config-enabled:false}", autoRefreshed = true) @Resource
@Value("${refresh-local-cache.api-config-enabled:false}") private RefreshLocalCacheConfigProperties refreshLocalCacheConfigProperties;
private boolean apiConfigCacheRefreshEnabled;
@NacosValue(value = "${refresh-local-cache.api-config-2-apps-enabled:false}", autoRefreshed = true)
@Value("${refresh-local-cache.api-config-2-apps-enabled:false}")
private boolean apiConfig2AppsCacheRefreshEnabled;
@NacosValue(value = "${refresh-local-cache.aggregate-config-enabled:false}", autoRefreshed = true)
@Value("${refresh-local-cache.aggregate-config-enabled:false}")
private boolean aggregateConfigCacheRefreshEnabled;
@NacosValue(value = "${refresh-local-cache.gateway-group-enabled:false}", autoRefreshed = true)
@Value("${refresh-local-cache.gateway-group-enabled:false}")
private boolean gatewayGroupCacheRefreshEnabled;
@NacosValue(value = "${refresh-local-cache.app-auth-enabled:false}", autoRefreshed = true)
@Value("${refresh-local-cache.app-auth-enabled:false}")
private boolean appAuthCacheRefreshEnabled;
@NacosValue(value = "${refresh-local-cache.flow-control-rule-enabled:false}", autoRefreshed = true)
@Value("${refresh-local-cache.flow-control-rule-enabled:false}")
private boolean flowControlRuleCacheRefreshEnabled;
@NacosValue(value = "${refresh-local-cache.rpc-service-enabled:false}", autoRefreshed = true)
@Value("${refresh-local-cache.rpc-service-enabled:false}")
private boolean rpcServiceCacheRefreshEnabled;
@Resource @Resource
private ConfigLoader configLoader; private ConfigLoader configLoader;
@@ -94,7 +73,7 @@ public class RefreshLocalCacheConfig {
@Scheduled(initialDelayString = "${refresh-local-cache.initial-delay-millis:300000}", @Scheduled(initialDelayString = "${refresh-local-cache.initial-delay-millis:300000}",
fixedRateString = "${refresh-local-cache.fixed-rate-millis:300000}") fixedRateString = "${refresh-local-cache.fixed-rate-millis:300000}")
public void refreshLocalCache() { public void refreshLocalCache() {
if (apiConfigCacheRefreshEnabled) { if (refreshLocalCacheConfigProperties.isApiConfigCacheRefreshEnabled()) {
LOGGER.debug("refresh api config local cache"); LOGGER.debug("refresh api config local cache");
try { try {
apiConfigService.refreshLocalCache(); apiConfigService.refreshLocalCache();
@@ -103,7 +82,7 @@ public class RefreshLocalCacheConfig {
} }
} }
if (apiConfig2AppsCacheRefreshEnabled) { if (refreshLocalCacheConfigProperties.isApiConfig2AppsCacheRefreshEnabled()) {
LOGGER.debug("refresh api config to apps local cache"); LOGGER.debug("refresh api config to apps local cache");
try { try {
apiConifg2appsService.refreshLocalCache(); apiConifg2appsService.refreshLocalCache();
@@ -112,7 +91,7 @@ public class RefreshLocalCacheConfig {
} }
} }
if (aggregateConfigCacheRefreshEnabled) { if (refreshLocalCacheConfigProperties.isAggregateConfigCacheRefreshEnabled()) {
LOGGER.debug("refresh aggregate config local cache"); LOGGER.debug("refresh aggregate config local cache");
try { try {
configLoader.refreshLocalCache(); configLoader.refreshLocalCache();
@@ -121,7 +100,7 @@ public class RefreshLocalCacheConfig {
} }
} }
if (gatewayGroupCacheRefreshEnabled) { if (refreshLocalCacheConfigProperties.isGatewayGroupCacheRefreshEnabled()) {
LOGGER.debug("refresh gateway group local cache"); LOGGER.debug("refresh gateway group local cache");
try { try {
gatewayGroupService.refreshLocalCache(); gatewayGroupService.refreshLocalCache();
@@ -130,7 +109,7 @@ public class RefreshLocalCacheConfig {
} }
} }
if (appAuthCacheRefreshEnabled) { if (refreshLocalCacheConfigProperties.isAppAuthCacheRefreshEnabled()) {
LOGGER.debug("refresh app auth local cache"); LOGGER.debug("refresh app auth local cache");
try { try {
appService.refreshLocalCache(); appService.refreshLocalCache();
@@ -139,7 +118,7 @@ public class RefreshLocalCacheConfig {
} }
} }
if (flowControlRuleCacheRefreshEnabled) { if (refreshLocalCacheConfigProperties.isFlowControlRuleCacheRefreshEnabled()) {
LOGGER.debug("refresh flow control rule local cache"); LOGGER.debug("refresh flow control rule local cache");
try { try {
resourceRateLimitConfigService.refreshLocalCache(); resourceRateLimitConfigService.refreshLocalCache();
@@ -148,7 +127,7 @@ public class RefreshLocalCacheConfig {
} }
} }
if (rpcServiceCacheRefreshEnabled) { if (refreshLocalCacheConfigProperties.isRpcServiceCacheRefreshEnabled()) {
LOGGER.debug("refresh rpc service local cache"); LOGGER.debug("refresh rpc service local cache");
try { try {
rpcInstanceService.refreshLocalCache(); rpcInstanceService.refreshLocalCache();

View File

@@ -0,0 +1,54 @@
/*
* Copyright (C) 2020 the original author or authors.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package we.config;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
/**
* {@link RefreshLocalCacheConfig} properties
*
* @author zhongjie
*/
@RefreshScope
@Component
@Data
public class RefreshLocalCacheConfigProperties {
@Value("${refresh-local-cache.api-config-enabled:false}")
private boolean apiConfigCacheRefreshEnabled;
@Value("${refresh-local-cache.api-config-2-apps-enabled:false}")
private boolean apiConfig2AppsCacheRefreshEnabled;
@Value("${refresh-local-cache.aggregate-config-enabled:false}")
private boolean aggregateConfigCacheRefreshEnabled;
@Value("${refresh-local-cache.gateway-group-enabled:false}")
private boolean gatewayGroupCacheRefreshEnabled;
@Value("${refresh-local-cache.app-auth-enabled:false}")
private boolean appAuthCacheRefreshEnabled;
@Value("${refresh-local-cache.flow-control-rule-enabled:false}")
private boolean flowControlRuleCacheRefreshEnabled;
@Value("${refresh-local-cache.rpc-service-enabled:false}")
private boolean rpcServiceCacheRefreshEnabled;
}

View File

@@ -14,32 +14,32 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package we.config; package we.config;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.ctrip.framework.apollo.model.ConfigChange;
import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration; import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils; import org.springframework.util.ObjectUtils;
import we.util.Constants; import we.util.Constants;
import we.util.WebUtils; import we.util.WebUtils;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
import java.util.*; import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream; import java.util.stream.Stream;
/** /**
* @author hongqiaowei * @author hongqiaowei
*/ */
@RefreshScope
@Configuration @Component
public class SystemConfig { public class SystemConfig {
private static final Logger log = LoggerFactory.getLogger(SystemConfig.class); private static final Logger log = LoggerFactory.getLogger(SystemConfig.class);
@@ -50,24 +50,25 @@ public class SystemConfig {
public static final String DEFAULT_GATEWAY_TEST_PREFIX0 = "/_proxytest/"; public static final String DEFAULT_GATEWAY_TEST_PREFIX0 = "/_proxytest/";
public String gatewayPrefix = DEFAULT_GATEWAY_PREFIX; private String gatewayPrefix = DEFAULT_GATEWAY_PREFIX;
public List<String> appHeaders = Stream.of("fizz-appid").collect(Collectors.toList()); private List<String> appHeaders = Stream.of("fizz-appid").collect(Collectors.toList());
public List<String> signHeaders = Stream.of("fizz-sign") .collect(Collectors.toList()); private List<String> signHeaders = Stream.of("fizz-sign") .collect(Collectors.toList());
public List<String> timestampHeaders = Stream.of("fizz-ts") .collect(Collectors.toList()); private List<String> timestampHeaders = Stream.of("fizz-ts") .collect(Collectors.toList());
public List<String> proxySetHeaders = new ArrayList<>();
public boolean aggregateTestAuth = false; private List<String> proxySetHeaders = new ArrayList<>();
private boolean aggregateTestAuth = false;
@NacosValue(value = "${route-timeout:0}", autoRefreshed = true)
@Value ( "${route-timeout:0}") @Value ( "${route-timeout:0}")
public long routeTimeout = 0; private long routeTimeout = 0;
public long getRouteTimeout() {
@NacosValue(value = "${gateway.aggr.proxy_set_headers:}", autoRefreshed = true) return routeTimeout;
}
@Value("${gateway.aggr.proxy_set_headers:}") @Value("${gateway.aggr.proxy_set_headers:}")
public void setProxySetHeaders(String hdrs) { public void setProxySetHeaders(String hdrs) {
if (StringUtils.isNotBlank(hdrs)) { if (StringUtils.isNotBlank(hdrs)) {
@@ -79,7 +80,10 @@ public class SystemConfig {
log.info("proxy set headers: " + hdrs); log.info("proxy set headers: " + hdrs);
} }
@NacosValue(value = "${gateway.prefix:/proxy}", autoRefreshed = true) public List<String> getProxySetHeaders() {
return proxySetHeaders;
}
@Value( "${gateway.prefix:/proxy}" ) @Value( "${gateway.prefix:/proxy}" )
public void setGatewayPrefix(String gp) { public void setGatewayPrefix(String gp) {
gatewayPrefix = gp; gatewayPrefix = gp;
@@ -87,7 +91,10 @@ public class SystemConfig {
log.info("gateway prefix: " + gatewayPrefix); log.info("gateway prefix: " + gatewayPrefix);
} }
@NacosValue(value = "${custom.header.appid:}", autoRefreshed = true) public String getGatewayPrefix() {
return gatewayPrefix;
}
@Value( "${custom.header.appid:}" ) @Value( "${custom.header.appid:}" )
public void setCustomAppHeaders(String hdrs) { public void setCustomAppHeaders(String hdrs) {
if (StringUtils.isNotBlank(hdrs)) { if (StringUtils.isNotBlank(hdrs)) {
@@ -101,7 +108,10 @@ public class SystemConfig {
log.info("app headers: " + appHeaders); log.info("app headers: " + appHeaders);
} }
@NacosValue(value = "${custom.header.sign:}", autoRefreshed = true) public List<String> getAppHeaders() {
return appHeaders;
}
@Value( "${custom.header.sign:}" ) @Value( "${custom.header.sign:}" )
public void setCustomSignHeaders(String hdrs) { public void setCustomSignHeaders(String hdrs) {
if (StringUtils.isNotBlank(hdrs)) { if (StringUtils.isNotBlank(hdrs)) {
@@ -114,7 +124,10 @@ public class SystemConfig {
log.info("sign headers: " + signHeaders); log.info("sign headers: " + signHeaders);
} }
@NacosValue(value = "${custom.header.ts:}", autoRefreshed = true) public List<String> getSignHeaders() {
return signHeaders;
}
@Value( "${custom.header.ts:}" ) @Value( "${custom.header.ts:}" )
public void setCustomTimestampHeaders(String hdrs) { public void setCustomTimestampHeaders(String hdrs) {
if (StringUtils.isNotBlank(hdrs)) { if (StringUtils.isNotBlank(hdrs)) {
@@ -127,27 +140,35 @@ public class SystemConfig {
log.info("timestamp headers: " + timestampHeaders); log.info("timestamp headers: " + timestampHeaders);
} }
@NacosValue(value = "${aggregate-test-auth:false}", autoRefreshed = true) public List<String> getTimestampHeaders() {
return timestampHeaders;
}
@Value( "${aggregate-test-auth:false}" ) @Value( "${aggregate-test-auth:false}" )
public void setAggregateTestAuth(boolean b) { public void setAggregateTestAuth(boolean b) {
aggregateTestAuth = b; aggregateTestAuth = b;
log.info("aggregate test auth: " + aggregateTestAuth); log.info("aggregate test auth: " + aggregateTestAuth);
} }
public boolean isAggregateTestAuth() {
return aggregateTestAuth;
}
// TODO: below to X // TODO: below to X
@Value("${log.response-body:false}")
private boolean logResponseBody; private boolean logResponseBody;
@Value("${log.headers:x}")
private String logHeaders; private String logHeaders;
private Set<String> logHeaderSet = new HashSet<>(); private Set<String> logHeaderSet = new HashSet<>();
@NacosValue(value = "${spring.profiles.active}")
@Value("${spring.profiles.active}") @Value("${spring.profiles.active}")
private String profile; private String profile;
public String getProfile() {
return profile;
}
public Set<String> getLogHeaderSet() { public Set<String> getLogHeaderSet() {
return logHeaderSet; return logHeaderSet;
} }
@@ -172,24 +193,6 @@ public class SystemConfig {
log.info("log header list: " + logHeaderSet.toString()); log.info("log header list: " + logHeaderSet.toString());
} }
@ApolloConfigChangeListener
private void configChangeListter(ConfigChangeEvent cce) {
cce.changedKeys().forEach(
k -> {
ConfigChange c = cce.getChange(k);
String p = c.getPropertyName();
String ov = c.getOldValue();
String nv = c.getNewValue();
log.info(p + " old: " + ov + ", new: " + nv);
if (p.equals("log.response-body")) {
this.updateLogResponseBody(Boolean.parseBoolean(nv));
} else if (p.equals("log.headers")) {
this.updateLogHeaders(nv);
}
}
);
}
private void updateLogResponseBody(boolean newValue) { private void updateLogResponseBody(boolean newValue) {
logResponseBody = newValue; logResponseBody = newValue;
this.afterLogResponseBodySet(); this.afterLogResponseBodySet();
@@ -200,7 +203,7 @@ public class SystemConfig {
afterLogHeadersSet(); afterLogHeadersSet();
} }
@NacosValue(value = "${log.response-body:false}", autoRefreshed = true) @Value("${log.response-body:false}")
public void setLogResponseBody(boolean logResponseBody) { public void setLogResponseBody(boolean logResponseBody) {
if (this.logResponseBody == logResponseBody) { if (this.logResponseBody == logResponseBody) {
return; return;
@@ -209,7 +212,7 @@ public class SystemConfig {
this.updateLogResponseBody(logResponseBody); this.updateLogResponseBody(logResponseBody);
} }
@NacosValue(value = "${log.headers:x}", autoRefreshed = true) @Value("${log.headers:x}")
public void setLogHeaders(String logHeaders) { public void setLogHeaders(String logHeaders) {
if (ObjectUtils.nullSafeEquals(this.logHeaders, logHeaders)) { if (ObjectUtils.nullSafeEquals(this.logHeaders, logHeaders)) {
return; return;

View File

@@ -19,7 +19,6 @@ package we.config;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.web.ServerProperties; import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties;
@@ -31,7 +30,7 @@ import org.springframework.web.reactive.config.EnableWebFlux;
import org.springframework.web.reactive.config.ResourceHandlerRegistry; import org.springframework.web.reactive.config.ResourceHandlerRegistry;
import org.springframework.web.reactive.config.WebFluxConfigurer; import org.springframework.web.reactive.config.WebFluxConfigurer;
import com.alibaba.nacos.api.config.annotation.NacosValue; import javax.annotation.Resource;
/** /**
* @author hongqiaowei * @author hongqiaowei
@@ -135,27 +134,15 @@ public class WebFluxConfig {
@Configuration @Configuration
@EnableWebFlux @EnableWebFlux
public static class FizzWebFluxConfigurer implements WebFluxConfigurer { public static class FizzWebFluxConfigurer implements WebFluxConfigurer {
@Resource
/** private WebFluxConfigProperties webFluxConfigProperties;
* Configure the maximum amount of disk space allowed for file parts. Default 100M (104857600)
*/
@NacosValue(value = "${server.fileUpload.maxDiskUsagePerPart:104857600}", autoRefreshed = true)
@Value( "${server.fileUpload.maxDiskUsagePerPart:104857600}" )
private long maxDiskUsagePerPart;
/**
* Maximum parts of multipart form-data, including form field parts; Default -1 no limit
*/
@NacosValue(value = "${server.fileUpload.maxParts:-1}", autoRefreshed = true)
@Value( "${server.fileUpload.maxParts:-1}" )
private int maxParts;
@Override @Override
public void configureHttpMessageCodecs(ServerCodecConfigurer configurer) { public void configureHttpMessageCodecs(ServerCodecConfigurer configurer) {
configurer.defaultCodecs().maxInMemorySize(-1); configurer.defaultCodecs().maxInMemorySize(-1);
SynchronossPartHttpMessageReader partReader = new SynchronossPartHttpMessageReader(); SynchronossPartHttpMessageReader partReader = new SynchronossPartHttpMessageReader();
partReader.setMaxParts(maxParts); partReader.setMaxParts(webFluxConfigProperties.getMaxParts());
partReader.setMaxDiskUsagePerPart(maxDiskUsagePerPart); partReader.setMaxDiskUsagePerPart(webFluxConfigProperties.getMaxDiskUsagePerPart());
MultipartHttpMessageReader multipartReader = new MultipartHttpMessageReader(partReader); MultipartHttpMessageReader multipartReader = new MultipartHttpMessageReader(partReader);
configurer.defaultCodecs().multipartReader(multipartReader); configurer.defaultCodecs().multipartReader(multipartReader);
} }

View File

@@ -0,0 +1,44 @@
/*
* Copyright (C) 2020 the original author or authors.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package we.config;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
/**
* {@link WebFluxConfig} properties
*
* @author zhongjie
*/
@RefreshScope
@Component
@Data
public class WebFluxConfigProperties {
/**
* Configure the maximum amount of disk space allowed for file parts. Default 100M (104857600)
*/
@Value( "${server.fileUpload.maxDiskUsagePerPart:104857600}" )
private long maxDiskUsagePerPart;
/**
* Maximum parts of multipart form-data, including form field parts; Default -1 no limit
*/
@Value( "${server.fileUpload.maxParts:-1}" )
private int maxParts;
}

View File

@@ -17,11 +17,11 @@
package we.controller; package we.controller;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
@@ -36,7 +36,6 @@ import we.util.Constants;
import we.util.DateTimeUtils; import we.util.DateTimeUtils;
import we.util.JacksonUtils; import we.util.JacksonUtils;
import javax.annotation.Resource;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
@@ -45,14 +44,13 @@ import java.util.Map;
/** /**
* @author hongqiaowei * @author hongqiaowei
*/ */
@RefreshScope
@RestController @RestController
@RequestMapping("/admin/flowStat") @RequestMapping("/admin/flowStat")
public class FlowControlController { public class FlowControlController {
private static final Logger log = LoggerFactory.getLogger(FlowControlController.class); private static final Logger log = LoggerFactory.getLogger(FlowControlController.class);
@NacosValue(value = "${flowControl:false}", autoRefreshed = true)
@Value("${flowControl:false}") @Value("${flowControl:false}")
private boolean flowControl; private boolean flowControl;

View File

@@ -17,8 +17,8 @@
package we.controller; package we.controller;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
@@ -42,10 +42,10 @@ import java.util.stream.Collectors;
* Fizz管理后台通过该控制器暴露的接口获取聚合配置相关信息 * Fizz管理后台通过该控制器暴露的接口获取聚合配置相关信息
* @author zhongjie * @author zhongjie
*/ */
@RefreshScope
@RestController @RestController
@RequestMapping(value = "/admin/managerConfig") @RequestMapping(value = "/admin/managerConfig")
public class ManagerConfigController { public class ManagerConfigController {
@NacosValue(value = "${fizz.manager.config.key:fizz-manager-key}", autoRefreshed = true)
@Value("${fizz.manager.config.key:fizz-manager-key}") @Value("${fizz.manager.config.key:fizz-manager-key}")
private String key; private String key;

View File

@@ -29,7 +29,6 @@ import javax.annotation.Resource;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order; import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer; import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils; import org.springframework.core.io.buffer.DataBufferUtils;
@@ -46,7 +45,6 @@ import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain; import org.springframework.web.server.WebFilterChain;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import io.netty.buffer.UnpooledByteBufAllocator; import io.netty.buffer.UnpooledByteBufAllocator;
import reactor.core.publisher.Flux; import reactor.core.publisher.Flux;
@@ -79,9 +77,8 @@ public class AggregateFilter implements WebFilter {
@Resource @Resource
private ConfigLoader configLoader; private ConfigLoader configLoader;
@NacosValue(value = "${need-auth:true}", autoRefreshed = true) @Resource
@Value("${need-auth:true}") private AggregateFilterProperties aggregateFilterProperties;
private boolean needAuth;
@Resource @Resource
private SystemConfig systemConfig; private SystemConfig systemConfig;
@@ -97,10 +94,10 @@ public class AggregateFilter implements WebFilter {
if (act == ApiConfig.Type.UNDEFINED) { if (act == ApiConfig.Type.UNDEFINED) {
String p = exchange.getRequest().getPath().value(); String p = exchange.getRequest().getPath().value();
if (StringUtils.startsWith(p, SystemConfig.DEFAULT_GATEWAY_TEST_PREFIX0)) { if (StringUtils.startsWith(p, SystemConfig.DEFAULT_GATEWAY_TEST_PREFIX0)) {
if (systemConfig.aggregateTestAuth) { if (systemConfig.isAggregateTestAuth()) {
return chain.filter(exchange); return chain.filter(exchange);
} }
} else if (needAuth) { } else if (aggregateFilterProperties.isNeedAuth()) {
return chain.filter(exchange); return chain.filter(exchange);
} }
} else if (act != ApiConfig.Type.SERVICE_AGGREGATE) { } else if (act != ApiConfig.Type.SERVICE_AGGREGATE) {

View File

@@ -0,0 +1,36 @@
/*
* Copyright (C) 2020 the original author or authors.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package we.filter;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
/**
* {@link AggregateFilter} properties
*
* @author zhongjie
*/
@RefreshScope
@Component
@Data
public class AggregateFilterProperties {
@Value("${need-auth:true}")
private boolean needAuth;
}

View File

@@ -18,12 +18,10 @@
package we.filter; package we.filter;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import io.netty.buffer.UnpooledByteBufAllocator; import io.netty.buffer.UnpooledByteBufAllocator;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order; import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer; import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils; import org.springframework.core.io.buffer.DataBufferUtils;
@@ -74,13 +72,8 @@ public class CallbackFilter extends FizzWebFilter {
@Resource @Resource
private DiscoveryClientUriSelector discoveryClientSelector; private DiscoveryClientUriSelector discoveryClientSelector;
@NacosValue(value = "${callback.push.dest:redis}", autoRefreshed = true) @Resource
@Value("${callback.push.dest:redis}") private CallbackFilterProperties callbackFilterProperties;
private String dest;
@NacosValue(value = "${callback.push.queue:fizz_callback_channel}", autoRefreshed = true)
@Value("${callback.push.queue:fizz_callback_channel}")
private String queue;
@Resource(name = AggregateRedisConfig.AGGREGATE_REACTIVE_REDIS_TEMPLATE) @Resource(name = AggregateRedisConfig.AGGREGATE_REACTIVE_REDIS_TEMPLATE)
private ReactiveStringRedisTemplate rt; private ReactiveStringRedisTemplate rt;
@@ -215,10 +208,10 @@ public class CallbackFilter extends FizzWebFilter {
b.append(Constants.Symbol.RIGHT_BRACE); b.append(Constants.Symbol.RIGHT_BRACE);
String msg = b.toString(); String msg = b.toString();
if ("kafka".equals(dest)) { // for internal use if ("kafka".equals(callbackFilterProperties.getDest())) { // for internal use
log.warn(msg, LogService.HANDLE_STGY, LogService.toKF(queue)); log.warn(msg, LogService.HANDLE_STGY, LogService.toKF(callbackFilterProperties.getQueue()));
} else { } else {
rt.convertAndSend(queue, msg).subscribe(); rt.convertAndSend(callbackFilterProperties.getQueue(), msg).subscribe();
} }
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("push callback req: " + msg); log.debug("push callback req: " + msg);

View File

@@ -0,0 +1,39 @@
/*
* Copyright (C) 2020 the original author or authors.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package we.filter;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
/**
* {@link CallbackFilter} properties
*
* @author zhongjie
*/
@RefreshScope
@Component
@Data
public class CallbackFilterProperties {
@Value("${callback.push.dest:redis}")
private String dest;
@Value("${callback.push.queue:fizz_callback_channel}")
private String queue;
}

View File

@@ -25,7 +25,6 @@ import javax.annotation.Resource;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order; import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
@@ -34,8 +33,6 @@ import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilterChain; import org.springframework.web.server.WebFilterChain;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import reactor.core.publisher.Mono; import reactor.core.publisher.Mono;
import reactor.core.publisher.SignalType; import reactor.core.publisher.SignalType;
import we.flume.clients.log4j2appender.LogService; import we.flume.clients.log4j2appender.LogService;
@@ -66,9 +63,8 @@ public class FlowControlFilter extends FizzWebFilter {
public static final String ADMIN_REQUEST = "$a"; public static final String ADMIN_REQUEST = "$a";
@NacosValue(value = "${flowControl:false}", autoRefreshed = true) @Resource
@Value("${flowControl:false}") private FlowControlFilterProperties flowControlFilterProperties;
private boolean flowControl;
@Resource @Resource
private ResourceRateLimitConfigService resourceRateLimitConfigService; private ResourceRateLimitConfigService resourceRateLimitConfigService;
@@ -92,7 +88,7 @@ public class FlowControlFilter extends FizzWebFilter {
exchange.getAttributes().put(ADMIN_REQUEST, Constants.Symbol.EMPTY); exchange.getAttributes().put(ADMIN_REQUEST, Constants.Symbol.EMPTY);
} }
if (flowControl && !adminReq) { if (flowControlFilterProperties.isFlowControl() && !adminReq) {
String service = WebUtils.getClientService(exchange); String service = WebUtils.getClientService(exchange);
// String reqPath = WebUtils.getClientReqPath(exchange); // String reqPath = WebUtils.getClientReqPath(exchange);
long currentTimeSlot = flowStat.currentTimeSlotId(); long currentTimeSlot = flowStat.currentTimeSlotId();

View File

@@ -0,0 +1,36 @@
/*
* Copyright (C) 2020 the original author or authors.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package we.filter;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
/**
* {@link FlowControlFilter} properties
*
* @author zhongjie
*/
@RefreshScope
@Component
@Data
public class FlowControlFilterProperties {
@Value("${flowControl:false}")
private boolean flowControl;
}

View File

@@ -17,6 +17,9 @@
package we.filter; package we.filter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.Order; import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;

View File

@@ -20,8 +20,6 @@ package we.fizz;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.ConfigurableApplicationContext;
import reactor.core.publisher.Flux; import reactor.core.publisher.Flux;
@@ -108,9 +106,8 @@ public class ConfigLoader {
@Resource(name = AGGREGATE_REACTIVE_REDIS_TEMPLATE) @Resource(name = AGGREGATE_REACTIVE_REDIS_TEMPLATE)
private ReactiveStringRedisTemplate reactiveStringRedisTemplate; private ReactiveStringRedisTemplate reactiveStringRedisTemplate;
@NacosValue(value = "${fizz.aggregate.read-local-config-flag:false}", autoRefreshed = true) @Resource
@Value("${fizz.aggregate.read-local-config-flag:false}") private ConfigLoaderProperties configLoaderProperties;
private Boolean readLocalConfigFlag;
private String formalPathPrefix; private String formalPathPrefix;
private int formalPathServiceNameStartIndex; private int formalPathServiceNameStartIndex;
@@ -228,7 +225,7 @@ public class ConfigLoader {
Map<String, ConfigInfo> resourceKey2ConfigInfoMapTmp = new ConcurrentHashMap<>(1024); Map<String, ConfigInfo> resourceKey2ConfigInfoMapTmp = new ConcurrentHashMap<>(1024);
Map<String, String> aggregateId2ResourceKeyMapTmp = new ConcurrentHashMap<>(1024); Map<String, String> aggregateId2ResourceKeyMapTmp = new ConcurrentHashMap<>(1024);
if (readLocalConfigFlag) { if (configLoaderProperties.getReadLocalConfigFlag()) {
File dir = new File("json"); File dir = new File("json");
if (dir.exists() && dir.isDirectory()) { if (dir.exists() && dir.isDirectory()) {
File[] files = dir.listFiles(); File[] files = dir.listFiles();

View File

@@ -0,0 +1,36 @@
/*
* Copyright (C) 2020 the original author or authors.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package we.fizz;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
/**
* {@link ConfigLoader} properties
*
* @author zhongjie
*/
@RefreshScope
@Component
@Data
public class ConfigLoaderProperties {
@Value("${fizz.aggregate.read-local-config-flag:false}")
private Boolean readLocalConfigFlag;
}

View File

@@ -349,7 +349,7 @@ public class RequestInput extends RPCInput implements IInput{
// add default headers // add default headers
SystemConfig systemConfig = this.getCurrentApplicationContext().getBean(SystemConfig.class); SystemConfig systemConfig = this.getCurrentApplicationContext().getBean(SystemConfig.class);
for (String hdr : systemConfig.proxySetHeaders) { for (String hdr : systemConfig.getProxySetHeaders()) {
if(inputContext.getStepContext().getInputReqHeader(hdr) != null) { if(inputContext.getStepContext().getInputReqHeader(hdr) != null) {
headers.addIfAbsent(hdr, (String) inputContext.getStepContext().getInputReqHeader(hdr)); headers.addIfAbsent(hdr, (String) inputContext.getStepContext().getInputReqHeader(hdr));
} }

View File

@@ -19,6 +19,7 @@ package we.log;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import org.springframework.data.redis.core.ReactiveStringRedisTemplate; import org.springframework.data.redis.core.ReactiveStringRedisTemplate;
import we.config.AggregateRedisConfig; import we.config.AggregateRedisConfig;
import we.config.AggregateRedisConfigProperties;
/** /**
* {@link LogSendService} impl class, using redis channel to send log * {@link LogSendService} impl class, using redis channel to send log
@@ -26,18 +27,22 @@ import we.config.AggregateRedisConfig;
* @author zhongjie * @author zhongjie
*/ */
public class RedisLogSendServiceImpl implements LogSendService { public class RedisLogSendServiceImpl implements LogSendService {
public RedisLogSendServiceImpl(AggregateRedisConfig aggregateRedisConfig, ReactiveStringRedisTemplate reactiveStringRedisTemplate) {
public RedisLogSendServiceImpl(AggregateRedisConfigProperties aggregateRedisConfigProperties,
AggregateRedisConfig aggregateRedisConfig, ReactiveStringRedisTemplate reactiveStringRedisTemplate) {
this.aggregateRedisConfigProperties = aggregateRedisConfigProperties;
this.aggregateRedisConfig = aggregateRedisConfig; this.aggregateRedisConfig = aggregateRedisConfig;
this.reactiveStringRedisTemplate = reactiveStringRedisTemplate; this.reactiveStringRedisTemplate = reactiveStringRedisTemplate;
} }
private AggregateRedisConfigProperties aggregateRedisConfigProperties;
private AggregateRedisConfig aggregateRedisConfig; private AggregateRedisConfig aggregateRedisConfig;
private ReactiveStringRedisTemplate reactiveStringRedisTemplate; private ReactiveStringRedisTemplate reactiveStringRedisTemplate;
@Override @Override
public void send(LogSend logSend) { public void send(LogSend logSend) {
if (aggregateRedisConfig.getSendLogOpen()) { if (aggregateRedisConfigProperties.isSendLogOpen()) {
reactiveStringRedisTemplate.convertAndSend(aggregateRedisConfig.getSendLogChannel(), JSON.toJSONString(logSend)).subscribe(); reactiveStringRedisTemplate.convertAndSend(aggregateRedisConfigProperties.getSendLogChannel(), JSON.toJSONString(logSend)).subscribe();
} }
} }
} }

View File

@@ -17,12 +17,10 @@
package we.plugin.auth; package we.plugin.auth;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.ReactiveStringRedisTemplate; import org.springframework.data.redis.core.ReactiveStringRedisTemplate;
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod; import org.springframework.http.HttpMethod;
@@ -57,21 +55,12 @@ public class ApiConfigService {
public static final String AUTH_MSG = "$authMsg"; public static final String AUTH_MSG = "$authMsg";
@NacosValue(value = "${fizz-api-config.key:fizz_api_config_route}", autoRefreshed = true)
@Value("${fizz-api-config.key:fizz_api_config_route}")
private String fizzApiConfig;
@NacosValue(value = "${fizz-api-config.channel:fizz_api_config_channel_route}", autoRefreshed = true)
@Value("${fizz-api-config.channel:fizz_api_config_channel_route}")
private String fizzApiConfigChannel;
public Map<String, ServiceConfig> serviceConfigMap = new HashMap<>(128); public Map<String, ServiceConfig> serviceConfigMap = new HashMap<>(128);
private Map<Integer, ApiConfig> apiConfigMap = new HashMap<>(128); private Map<Integer, ApiConfig> apiConfigMap = new HashMap<>(128);
@NacosValue(value = "${need-auth:true}", autoRefreshed = true) @Resource
@Value("${need-auth:true}") private ApiConfigServiceProperties apiConfigServiceProperties;
private boolean needAuth;
@Resource(name = AggregateRedisConfig.AGGREGATE_REACTIVE_REDIS_TEMPLATE) @Resource(name = AggregateRedisConfig.AGGREGATE_REACTIVE_REDIS_TEMPLATE)
private ReactiveStringRedisTemplate rt; private ReactiveStringRedisTemplate rt;
@@ -104,7 +93,7 @@ public class ApiConfigService {
Map<Integer, ApiConfig> apiConfigMapTmp = new HashMap<>(128); Map<Integer, ApiConfig> apiConfigMapTmp = new HashMap<>(128);
Map<String, ServiceConfig> serviceConfigMapTmp = new HashMap<>(128); Map<String, ServiceConfig> serviceConfigMapTmp = new HashMap<>(128);
final Throwable[] throwable = new Throwable[1]; final Throwable[] throwable = new Throwable[1];
Throwable error = Mono.just(Objects.requireNonNull(rt.opsForHash().entries(fizzApiConfig) Throwable error = Mono.just(Objects.requireNonNull(rt.opsForHash().entries(apiConfigServiceProperties.getFizzApiConfig())
.defaultIfEmpty(new AbstractMap.SimpleEntry<>(ReactorUtils.OBJ, ReactorUtils.OBJ)).onErrorStop().doOnError(t -> log.info(null, t)) .defaultIfEmpty(new AbstractMap.SimpleEntry<>(ReactorUtils.OBJ, ReactorUtils.OBJ)).onErrorStop().doOnError(t -> log.info(null, t))
.concatMap(e -> { .concatMap(e -> {
Object k = e.getKey(); Object k = e.getKey();
@@ -148,14 +137,14 @@ public class ApiConfigService {
private Mono<Throwable> lsnApiConfigChange() { private Mono<Throwable> lsnApiConfigChange() {
final Throwable[] throwable = new Throwable[1]; final Throwable[] throwable = new Throwable[1];
final boolean[] b = {false}; final boolean[] b = {false};
rt.listenToChannel(fizzApiConfigChannel).doOnError(t -> { rt.listenToChannel(apiConfigServiceProperties.getFizzApiConfigChannel()).doOnError(t -> {
throwable[0] = t; throwable[0] = t;
b[0] = false; b[0] = false;
log.error("lsn " + fizzApiConfigChannel, t); log.error("lsn " + apiConfigServiceProperties.getFizzApiConfigChannel(), t);
}).doOnSubscribe( }).doOnSubscribe(
s -> { s -> {
b[0] = true; b[0] = true;
log.info("success to lsn on " + fizzApiConfigChannel); log.info("success to lsn on " + apiConfigServiceProperties.getFizzApiConfigChannel());
} }
).doOnNext(msg -> { ).doOnNext(msg -> {
String json = msg.getMessage(); String json = msg.getMessage();
@@ -314,13 +303,13 @@ public class ApiConfigService {
authMsg = deny; authMsg = deny;
} }
if (SystemConfig.DEFAULT_GATEWAY_TEST_PREFIX0.equals(WebUtils.getClientReqPathPrefix(exchange))) { if (SystemConfig.DEFAULT_GATEWAY_TEST_PREFIX0.equals(WebUtils.getClientReqPathPrefix(exchange))) {
if (systemConfig.aggregateTestAuth) { if (systemConfig.isAggregateTestAuth()) {
return logAndResult(authMsg); return logAndResult(authMsg);
} else { } else {
return Mono.just(Access.YES); return Mono.just(Access.YES);
} }
} }
if (!needAuth) { if (!apiConfigServiceProperties.isNeedAuth()) {
return Mono.just(Access.YES); return Mono.just(Access.YES);
} else { } else {
return logAndResult(authMsg); return logAndResult(authMsg);
@@ -392,7 +381,7 @@ public class ApiConfigService {
} }
private String getTimestamp(HttpHeaders reqHdrs) { private String getTimestamp(HttpHeaders reqHdrs) {
List<String> tsHdrs = systemConfig.timestampHeaders; List<String> tsHdrs = systemConfig.getTimestampHeaders();
for (int i = 0; i < tsHdrs.size(); i++) { for (int i = 0; i < tsHdrs.size(); i++) {
String a = reqHdrs.getFirst(tsHdrs.get(i)); String a = reqHdrs.getFirst(tsHdrs.get(i));
if (a != null) { if (a != null) {
@@ -403,7 +392,7 @@ public class ApiConfigService {
} }
private String getSign(HttpHeaders reqHdrs) { private String getSign(HttpHeaders reqHdrs) {
List<String> signHdrs = systemConfig.signHeaders; List<String> signHdrs = systemConfig.getSignHeaders();
for (int i = 0; i < signHdrs.size(); i++) { for (int i = 0; i < signHdrs.size(); i++) {
String a = reqHdrs.getFirst(signHdrs.get(i)); String a = reqHdrs.getFirst(signHdrs.get(i));
if (a != null) { if (a != null) {

View File

@@ -0,0 +1,41 @@
/*
* Copyright (C) 2020 the original author or authors.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package we.plugin.auth;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
/**
* {@link ApiConfigService} properties
*
* @author zhongjie
*/
@RefreshScope
@Component
@Data
public class ApiConfigServiceProperties {
@Value("${fizz-api-config.key:fizz_api_config_route}")
private String fizzApiConfig;
@Value("${fizz-api-config.channel:fizz_api_config_channel_route}")
private String fizzApiConfigChannel;
@Value("${need-auth:true}")
private boolean needAuth;
}

View File

@@ -17,11 +17,9 @@
package we.plugin.stat; package we.plugin.stat;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.ReactiveStringRedisTemplate; import org.springframework.data.redis.core.ReactiveStringRedisTemplate;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.ServerWebExchange;
@@ -64,17 +62,8 @@ public class StatPluginFilter extends PluginFilter {
private static final String reqTime = "\"reqTime\":"; private static final String reqTime = "\"reqTime\":";
@NacosValue(value = "${stat.open:false}", autoRefreshed = true) @Resource
@Value("${stat.open:false}") private StatPluginFilterProperties statPluginFilterProperties;
private boolean statOpen = false;
@NacosValue(value = "${stat.channel:fizz_access_stat}", autoRefreshed = true)
@Value("${stat.channel:fizz_access_stat}")
private String fizzAccessStatChannel;
@NacosValue(value = "${stat.topic:}", autoRefreshed = true)
@Value("${stat.topic:}")
private String fizzAccessStatTopic;
@Resource(name = AggregateRedisConfig.AGGREGATE_REACTIVE_REDIS_TEMPLATE) @Resource(name = AggregateRedisConfig.AGGREGATE_REACTIVE_REDIS_TEMPLATE)
private ReactiveStringRedisTemplate rt; private ReactiveStringRedisTemplate rt;
@@ -99,7 +88,7 @@ public class StatPluginFilter extends PluginFilter {
@Override @Override
public Mono<Void> doFilter(ServerWebExchange exchange, Map<String, Object> config, String fixedConfig) { public Mono<Void> doFilter(ServerWebExchange exchange, Map<String, Object> config, String fixedConfig) {
if (statOpen) { if (statPluginFilterProperties.isStatOpen()) {
StringBuilder b = ThreadContext.getStringBuilder(); StringBuilder b = ThreadContext.getStringBuilder();
b.append(Constants.Symbol.LEFT_BRACE); b.append(Constants.Symbol.LEFT_BRACE);
b.append(ip); toJsonStringValue(b, WebUtils.getOriginIp(exchange)); b.append(Constants.Symbol.COMMA); b.append(ip); toJsonStringValue(b, WebUtils.getOriginIp(exchange)); b.append(Constants.Symbol.COMMA);
@@ -116,10 +105,10 @@ public class StatPluginFilter extends PluginFilter {
b.append(reqTime) .append(System.currentTimeMillis()); b.append(reqTime) .append(System.currentTimeMillis());
b.append(Constants.Symbol.RIGHT_BRACE); b.append(Constants.Symbol.RIGHT_BRACE);
if (StringUtils.isBlank(fizzAccessStatTopic)) { if (StringUtils.isBlank(statPluginFilterProperties.getFizzAccessStatTopic())) {
rt.convertAndSend(fizzAccessStatChannel, b.toString()).subscribe(); rt.convertAndSend(statPluginFilterProperties.getFizzAccessStatChannel(), b.toString()).subscribe();
} else { } else {
log.warn(b.toString(), LogService.HANDLE_STGY, LogService.toKF(fizzAccessStatTopic)); // for internal use log.warn(b.toString(), LogService.HANDLE_STGY, LogService.toKF(statPluginFilterProperties.getFizzAccessStatTopic())); // for internal use
} }
} }

View File

@@ -0,0 +1,41 @@
/*
* Copyright (C) 2020 the original author or authors.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package we.plugin.stat;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
/**
* {@link StatPluginFilter} properties
*
* @author zhongjie
*/
@RefreshScope
@Component
@Data
public class StatPluginFilterProperties {
@Value("${stat.open:false}")
private boolean statOpen = false;
@Value("${stat.channel:fizz_access_stat}")
private String fizzAccessStatChannel;
@Value("${stat.topic:}")
private String fizzAccessStatTopic;
}

View File

@@ -75,7 +75,7 @@ public class CallbackService {
@PostConstruct @PostConstruct
public void postConstruct() { public void postConstruct() {
aggrConfigPrefix = systemConfig.gatewayPrefix + '/'; aggrConfigPrefix = systemConfig.getGatewayPrefix() + '/';
} }
public Mono<? extends Void> requestBackends(ServerWebExchange exchange, HttpHeaders headers, DataBuffer body, CallbackConfig cc, Map<String, ServiceInstance> service2instMap) { public Mono<? extends Void> requestBackends(ServerWebExchange exchange, HttpHeaders headers, DataBuffer body, CallbackConfig cc, Map<String, ServiceInstance> service2instMap) {

View File

@@ -10,7 +10,7 @@ import reactor.util.function.Tuple2;
* @author zhongjie * @author zhongjie
*/ */
@ConditionalOnExpression("${nacos.discovery.enabled} == false and ${eureka.client.enabled} == false") @ConditionalOnExpression("${spring.cloud.nacos.discovery.enabled} == false and ${eureka.client.enabled} == false")
@Service @Service
public class DisableDiscoveryUriSelector implements DiscoveryClientUriSelector { public class DisableDiscoveryUriSelector implements DiscoveryClientUriSelector {
@Override @Override

View File

@@ -133,8 +133,8 @@ public class FizzWebClient {
Mono<ClientResponse> cr = req.exchange(); Mono<ClientResponse> cr = req.exchange();
if (timeout == 0) { if (timeout == 0) {
if (systemConfig.routeTimeout != 0) { if (systemConfig.getRouteTimeout() != 0) {
timeout = systemConfig.routeTimeout; timeout = systemConfig.getRouteTimeout();
} }
} }
if (timeout != 0) { if (timeout != 0) {

View File

@@ -1,19 +1,15 @@
package we.proxy; package we.proxy;
import com.alibaba.boot.nacos.discovery.properties.NacosDiscoveryProperties; import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.boot.nacos.discovery.properties.Register;
import com.alibaba.nacos.api.annotation.NacosInjected; import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.naming.pojo.Instance;
import com.netflix.appinfo.InstanceInfo;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import reactor.util.function.Tuple2;
import reactor.util.function.Tuples;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
import java.util.Collections; import java.util.Collections;
@@ -24,7 +20,7 @@ import java.util.List;
* *
* @author zhongjie * @author zhongjie
*/ */
@ConditionalOnProperty(value = "nacos.discovery.enabled") @ConditionalOnProperty(value = "spring.cloud.nacos.discovery.enabled")
@Service @Service
public class NacosUriSelector extends AbstractDiscoveryClientUriSelector { public class NacosUriSelector extends AbstractDiscoveryClientUriSelector {
private static final Logger log = LoggerFactory.getLogger(NacosUriSelector.class); private static final Logger log = LoggerFactory.getLogger(NacosUriSelector.class);
@@ -35,7 +31,7 @@ public class NacosUriSelector extends AbstractDiscoveryClientUriSelector {
@NacosInjected @NacosInjected
private NamingService naming; private NamingService naming;
private NacosDiscoveryProperties discoveryProperties; final private NacosDiscoveryProperties discoveryProperties;
private String groupName; private String groupName;
private List<String> clusterNameList; private List<String> clusterNameList;
private boolean useGroupName; private boolean useGroupName;
@@ -43,18 +39,14 @@ public class NacosUriSelector extends AbstractDiscoveryClientUriSelector {
@PostConstruct @PostConstruct
public void init() { public void init() {
Register register = discoveryProperties.getRegister(); this.groupName = discoveryProperties.getGroup();
if (register != null) { if (StringUtils.hasText(groupName)) {
this.groupName = register.getGroupName(); this.useGroupName = true;
if (StringUtils.hasText(groupName)) { }
this.useGroupName = true; String clusterName = discoveryProperties.getClusterName();
} if (StringUtils.hasText(clusterName)) {
String clusterName = register.getClusterName(); this.userClusterName = true;
if (StringUtils.hasText(clusterName)) { this.clusterNameList = Collections.singletonList(clusterName);
this.userClusterName = true;
this.clusterNameList = Collections.singletonList(clusterName);
}
} }
} }

View File

@@ -17,7 +17,6 @@
package we.proxy.dubbo; package we.proxy.dubbo;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair; import org.apache.commons.lang3.tuple.Pair;
import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.ApplicationConfig;
@@ -27,7 +26,6 @@ import org.apache.dubbo.config.utils.ReferenceConfigCache;
import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.service.GenericException; import org.apache.dubbo.rpc.service.GenericException;
import org.apache.dubbo.rpc.service.GenericService; import org.apache.dubbo.rpc.service.GenericService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils; import org.springframework.util.CollectionUtils;
@@ -35,9 +33,9 @@ import reactor.core.publisher.Mono;
import we.fizz.exception.FizzException; import we.fizz.exception.FizzException;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.Duration; import java.time.Duration;
import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
@@ -49,10 +47,8 @@ import java.util.concurrent.CompletableFuture;
*/ */
@Service @Service
public class ApacheDubboGenericService { public class ApacheDubboGenericService {
@Resource
@NacosValue(value = "${fizz-dubbo-client.address}") private ApacheDubboGenericServiceProperties apacheDubboGenericServiceProperties;
@Value("${fizz-dubbo-client.address}")
private String zookeeperAddress = "";
@PostConstruct @PostConstruct
public void afterPropertiesSet() { public void afterPropertiesSet() {
@@ -63,7 +59,7 @@ public class ApacheDubboGenericService {
ApplicationConfig applicationConfig = new ApplicationConfig(); ApplicationConfig applicationConfig = new ApplicationConfig();
applicationConfig.setName("fizz_proxy"); applicationConfig.setName("fizz_proxy");
RegistryConfig registryConfig = new RegistryConfig(); RegistryConfig registryConfig = new RegistryConfig();
registryConfig.setAddress(zookeeperAddress); registryConfig.setAddress(apacheDubboGenericServiceProperties.getZookeeperAddress());
ReferenceConfig<GenericService> referenceConfig = new ReferenceConfig<>(); ReferenceConfig<GenericService> referenceConfig = new ReferenceConfig<>();
referenceConfig.setInterface(serviceName); referenceConfig.setInterface(serviceName);
applicationConfig.setRegistry(registryConfig); applicationConfig.setRegistry(registryConfig);

View File

@@ -0,0 +1,35 @@
/*
* Copyright (C) 2020 the original author or authors.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package we.proxy.dubbo;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
/**
* {@link ApacheDubboGenericService} properties
*
* @author zhongjie
*/
@RefreshScope
@Component
@Data
public class ApacheDubboGenericServiceProperties {
@Value("${fizz-dubbo-client.address}")
private String zookeeperAddress = "";
}

View File

@@ -133,19 +133,13 @@
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.alibaba.boot</groupId> <groupId>com.alibaba.cloud</groupId>
<artifactId>nacos-config-spring-boot-starter</artifactId> <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.alibaba.boot</groupId> <groupId>com.alibaba.cloud</groupId>
<artifactId>nacos-discovery-spring-boot-starter</artifactId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency> </dependency>
<dependency> <dependency>

View File

@@ -118,19 +118,13 @@
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.alibaba.boot</groupId> <groupId>com.alibaba.cloud</groupId>
<artifactId>nacos-config-spring-boot-starter</artifactId> <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.alibaba.boot</groupId> <groupId>com.alibaba.cloud</groupId>
<artifactId>nacos-discovery-spring-boot-starter</artifactId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency> </dependency>
<dependency> <dependency>

20
pom.xml
View File

@@ -9,7 +9,7 @@
<spring-framework.version>5.2.15.RELEASE</spring-framework.version> <spring-framework.version>5.2.15.RELEASE</spring-framework.version>
<reactor-bom.version>Dysprosium-SR20</reactor-bom.version> <reactor-bom.version>Dysprosium-SR20</reactor-bom.version>
<lettuce.version>5.3.7.RELEASE</lettuce.version> <lettuce.version>5.3.7.RELEASE</lettuce.version>
<nacos.version>0.2.7</nacos.version> <nacos.cloud.version>2.2.5.RELEASE</nacos.cloud.version>
<netty.version>4.1.65.Final</netty.version> <netty.version>4.1.65.Final</netty.version>
<httpcore.version>4.4.14</httpcore.version> <httpcore.version>4.4.14</httpcore.version>
<log4j2.version>2.13.3</log4j2.version> <log4j2.version>2.13.3</log4j2.version>
@@ -200,9 +200,9 @@
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.alibaba.boot</groupId> <groupId>com.alibaba.cloud</groupId>
<artifactId>nacos-config-spring-boot-starter</artifactId> <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
<version>${nacos.version}</version> <version>${nacos.cloud.version}</version>
<exclusions> <exclusions>
<exclusion> <exclusion>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
@@ -212,9 +212,15 @@
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.alibaba.boot</groupId> <groupId>com.alibaba.cloud</groupId>
<artifactId>nacos-discovery-spring-boot-starter</artifactId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
<version>${nacos.version}</version> <version>${nacos.cloud.version}</version>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency> </dependency>
<dependency> <dependency>