pull/632/head
fangjian0423 6 years ago
parent 7f9781bde4
commit 6d89d556bf

@ -152,6 +152,11 @@
<artifactId>sentinel-zuul-adapter</artifactId>
<version>${sentinel.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-spring-cloud-gateway-adapter</artifactId>
<version>${sentinel.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-transport-simple-http</artifactId>
@ -192,6 +197,11 @@
<artifactId>sentinel-spring-webflux-adapter</artifactId>
<version>${sentinel.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-api-gateway-adapter-common</artifactId>
<version>${sentinel.version}</version>
</dependency>

@ -27,6 +27,12 @@
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-api-gateway-adapter-common</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-datasource-nacos</artifactId>

@ -6,6 +6,8 @@ import java.util.Optional;
import org.springframework.cloud.alibaba.sentinel.datasource.config.AbstractDataSourceProperties;
import org.springframework.util.StringUtils;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiDefinition;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule;
import com.alibaba.csp.sentinel.slots.block.AbstractRule;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
@ -40,7 +42,15 @@ public enum RuleType {
/**
* authority
*/
AUTHORITY("authority", AuthorityRule.class);
AUTHORITY("authority", AuthorityRule.class),
/**
* gateway flow
*/
GATEWAY("gateway-flow", GatewayFlowRule.class),
/**
* api
*/
API("api", ApiDefinition.class);
/**
* alias for {@link AbstractRule}

@ -5,6 +5,8 @@ import javax.validation.constraints.NotNull;
import org.springframework.cloud.alibaba.sentinel.datasource.RuleType;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.GatewayApiDefinitionManager;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayRuleManager;
import com.alibaba.csp.sentinel.datasource.AbstractDataSource;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRuleManager;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
@ -82,6 +84,12 @@ public class AbstractDataSourceProperties {
case AUTHORITY:
AuthorityRuleManager.register2Property(dataSource.getProperty());
break;
case GATEWAY:
GatewayRuleManager.register2Property(dataSource.getProperty());
break;
case API:
GatewayApiDefinitionManager.register2Property(dataSource.getProperty());
break;
default:
break;
}

@ -1,7 +1,20 @@
package org.springframework.cloud.alibaba.sentinel.datasource.converter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.alibaba.sentinel.datasource.RuleType;
import org.springframework.util.StringUtils;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiDefinition;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule;
import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.slots.block.AbstractRule;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
@ -13,15 +26,6 @@ import com.alibaba.csp.sentinel.slots.system.SystemRule;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.alibaba.sentinel.datasource.RuleType;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;
/**
* Convert sentinel rules for json or xml array Using strict mode to parse json or xml
@ -34,8 +38,8 @@ import java.util.Optional;
* @see ParamFlowRule
* @see ObjectMapper
*/
public abstract class SentinelConverter<T extends AbstractRule>
implements Converter<String, List<AbstractRule>> {
public abstract class SentinelConverter<T extends Object>
implements Converter<String, Collection<Object>> {
private static final Logger log = LoggerFactory.getLogger(SentinelConverter.class);
@ -49,11 +53,20 @@ public abstract class SentinelConverter<T extends AbstractRule>
}
@Override
public List<AbstractRule> convert(String source) {
List<AbstractRule> ruleList = new ArrayList<>();
public Collection<Object> convert(String source) {
Collection<Object> ruleCollection;
// hard code
if (ruleClass == GatewayFlowRule.class || ruleClass == ApiDefinition.class) {
ruleCollection = new HashSet<>();
}
else {
ruleCollection = new ArrayList<>();
}
if (StringUtils.isEmpty(source)) {
log.warn("converter can not convert rules because source is empty");
return ruleList;
return ruleCollection;
}
try {
List sourceArray = objectMapper.readValue(source,
@ -70,11 +83,11 @@ public abstract class SentinelConverter<T extends AbstractRule>
}
Optional.ofNullable(convertRule(item))
.ifPresent(convertRule -> ruleList.add(convertRule));
.ifPresent(convertRule -> ruleCollection.add(convertRule));
});
if (ruleList.size() != sourceArray.size()) {
throw new IllegalArgumentException("convert " + ruleList.size()
if (ruleCollection.size() != sourceArray.size()) {
throw new IllegalArgumentException("convert " + ruleCollection.size()
+ " rules but there are " + sourceArray.size()
+ " rules from datasource. RuleClass: "
+ ruleClass.getSimpleName());
@ -83,12 +96,12 @@ public abstract class SentinelConverter<T extends AbstractRule>
catch (Exception e) {
throw new RuntimeException("convert error: " + e.getMessage(), e);
}
return ruleList;
return ruleCollection;
}
private AbstractRule convertRule(String ruleStr) {
private Object convertRule(String ruleStr) {
try {
final AbstractRule rule = objectMapper.readValue(ruleStr, ruleClass);
final Object rule = objectMapper.readValue(ruleStr, ruleClass);
RuleType ruleType = RuleType.getByClass(ruleClass).get();
switch (ruleType) {
case FLOW:

@ -46,7 +46,7 @@ public class SentinelConverterTests {
@Test
public void testJsonConverter() {
JsonConverter jsonConverter = new JsonConverter(objectMapper, FlowRule.class);
List<FlowRule> flowRules = jsonConverter
List<FlowRule> flowRules = (List<FlowRule>) jsonConverter
.convert(readFileContent("classpath: flowrule.json"));
assertEquals("json converter flow rule size was wrong", 1, flowRules.size());
assertEquals("json converter flow rule resource name was wrong", "resource",
@ -67,7 +67,7 @@ public class SentinelConverterTests {
@Test
public void testConverterEmptyContent() {
JsonConverter jsonConverter = new JsonConverter(objectMapper, FlowRule.class);
List<FlowRule> flowRules = jsonConverter.convert("");
List<FlowRule> flowRules = (List<FlowRule>) jsonConverter.convert("");
assertEquals("json converter flow rule size was not empty", 0, flowRules.size());
}
@ -86,7 +86,7 @@ public class SentinelConverterTests {
@Test
public void testXmlConverter() {
XmlConverter jsonConverter = new XmlConverter(xmlMapper, FlowRule.class);
List<FlowRule> flowRules = jsonConverter
List<FlowRule> flowRules = (List<FlowRule>) jsonConverter
.convert(readFileContent("classpath: flowrule.xml"));
assertEquals("xml converter flow rule size was wrong", 2, flowRules.size());
assertEquals("xml converter flow rule1 resource name was wrong", "resource",

@ -17,12 +17,21 @@
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
<scope>provided</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-zuul-adapter</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-spring-cloud-gateway-adapter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>

@ -0,0 +1,91 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.alibaba.sentinel.zuul;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import javax.annotation.PostConstruct;
import com.alibaba.csp.sentinel.adapter.gateway.sc.SentinelGatewayFilter;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.alibaba.csp.sentinel.adapter.gateway.sc.exception.SentinelGatewayBlockExceptionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.result.view.ViewResolver;
/**
* @author <a href="mailto:fangjian0423@gmail.com">Jim</a>
*/
@Configuration
@ConditionalOnClass(GlobalFilter.class)
@ConditionalOnProperty(prefix = "spring.cloud.sentinel.spring-cloud-gateway", name = "enabled", havingValue = "true",
matchIfMissing = true)
public class SentinelSpringCloudGatewayAutoConfiguration {
private static final Logger logger = LoggerFactory
.getLogger(SentinelSpringCloudGatewayAutoConfiguration.class);
private final List<ViewResolver> viewResolvers;
private final ServerCodecConfigurer serverCodecConfigurer;
@Autowired
private Optional<BlockRequestHandler> blockRequestHandlerOptional;
@PostConstruct
private void init() {
blockRequestHandlerOptional
.ifPresent(GatewayCallbackManager::setBlockHandler);
}
public SentinelSpringCloudGatewayAutoConfiguration(
ObjectProvider<List<ViewResolver>> viewResolversProvider,
ServerCodecConfigurer serverCodecConfigurer) {
this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
this.serverCodecConfigurer = serverCodecConfigurer;
}
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public SentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler() {
// Register the block exception handler for Spring Cloud Gateway.
logger.info("[Sentinel SpringCloudGateway] register SentinelGatewayBlockExceptionHandler");
return new SentinelGatewayBlockExceptionHandler(viewResolvers,
serverCodecConfigurer);
}
@Bean
@Order(-1)
public GlobalFilter sentinelGatewayFilter() {
logger.info("[Sentinel SpringCloudGateway] register SentinelGatewayFilter");
return new SentinelGatewayFilter();
}
}

@ -16,22 +16,28 @@
package org.springframework.cloud.alibaba.sentinel.zuul;
import static org.springframework.cloud.commons.util.InetUtilsProperties.PREFIX;
import java.util.Optional;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.alibaba.sentinel.zuul.handler.FallBackProviderHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
import com.alibaba.csp.sentinel.adapter.gateway.zuul.callback.DefaultRequestOriginParser;
import com.alibaba.csp.sentinel.adapter.gateway.zuul.callback.RequestOriginParser;
import com.alibaba.csp.sentinel.adapter.gateway.zuul.callback.ZuulGatewayCallbackManager;
import com.alibaba.csp.sentinel.adapter.gateway.zuul.filters.SentinelZuulErrorFilter;
import com.alibaba.csp.sentinel.adapter.gateway.zuul.filters.SentinelZuulPostFilter;
import com.alibaba.csp.sentinel.adapter.gateway.zuul.filters.SentinelZuulPreFilter;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.http.ZuulServlet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.alibaba.sentinel.zuul.handler.FallBackProviderHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
/**
* Sentinel Spring Cloud Zuul AutoConfiguration
@ -39,35 +45,71 @@ import com.netflix.zuul.ZuulFilter;
* @author tiger
*/
@Configuration
@ConditionalOnProperty(prefix = PREFIX, name = "enabled", havingValue = "true", matchIfMissing = true)
@ConditionalOnClass(ZuulServlet.class)
@ConditionalOnProperty(prefix = SentinelZuulAutoConfiguration.PREFIX, name = "enabled", havingValue = "true",
matchIfMissing = true)
public class SentinelZuulAutoConfiguration {
@Bean
@ConditionalOnMissingBean(RequestOriginParser.class)
public RequestOriginParser requestOriginParser() {
return new DefaultRequestOriginParser();
}
@Bean
public ZuulFilter sentinelZuulPreFilter() {
// We can also provider the filter order in the constructor.
return new SentinelZuulPreFilter();
}
@Bean
public ZuulFilter sentinelZuulPostFilter() {
return new SentinelZuulPostFilter();
}
@Bean
public ZuulFilter sentinelZuulErrorFilter() {
return new SentinelZuulErrorFilter();
}
@Bean
public FallBackProviderHandler fallBackProviderListener(
DefaultListableBeanFactory beanFactory) {
return new FallBackProviderHandler(beanFactory);
}
private static final Logger logger = LoggerFactory
.getLogger(SentinelZuulAutoConfiguration.class);
public static final String PREFIX = "spring.cloud.sentinel.zuul";
@Autowired
private Environment environment;
@Autowired
private Optional<RequestOriginParser> requestOriginParserOptional;
@PostConstruct
private void init() {
requestOriginParserOptional
.ifPresent(ZuulGatewayCallbackManager::setOriginParser);
}
@Bean
public ZuulFilter sentinelZuulPreFilter() {
String preOrderStr = environment.getProperty(PREFIX + "." + "order.pre");
int order = 10000;
try {
order = Integer.parseInt(preOrderStr);
} catch (NumberFormatException e) {
// ignore
}
logger.info("[Sentinel Zuul] register SentinelZuulPreFilter {}", order);
return new SentinelZuulPreFilter(order);
}
@Bean
public ZuulFilter sentinelZuulPostFilter() {
String postOrderStr = environment.getProperty(PREFIX + "." + "order.post");
int order = 1000;
try {
order = Integer.parseInt(postOrderStr);
} catch (NumberFormatException e) {
// ignore
}
logger.info("[Sentinel Zuul] register SentinelZuulPostFilter {}", order);
return new SentinelZuulPostFilter(order);
}
@Bean
public ZuulFilter sentinelZuulErrorFilter() {
String errorOrderStr = environment.getProperty(PREFIX + "." + "order.error");
int order = -1;
try {
order = Integer.parseInt(errorOrderStr);
} catch (NumberFormatException e) {
// ignore
}
logger.info("[Sentinel Zuul] register SentinelZuulErrorFilter {}", order);
return new SentinelZuulErrorFilter(order);
}
@Bean
public FallBackProviderHandler fallBackProviderHandler(
DefaultListableBeanFactory beanFactory) {
return new FallBackProviderHandler(beanFactory);
}
}

@ -2,11 +2,11 @@ package org.springframework.cloud.alibaba.sentinel.zuul.handler;
import java.util.Map;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.util.CollectionUtils;
import com.alibaba.csp.sentinel.adapter.gateway.zuul.fallback.DefaultBlockFallbackProvider;
import com.alibaba.csp.sentinel.adapter.gateway.zuul.fallback.ZuulBlockFallbackManager;
@ -30,7 +30,7 @@ public class FallBackProviderHandler implements SmartInitializingSingleton {
public void afterSingletonsInstantiated() {
Map<String, ZuulBlockFallbackProvider> providerMap = beanFactory
.getBeansOfType(ZuulBlockFallbackProvider.class);
if (MapUtils.isNotEmpty(providerMap)) {
if (!CollectionUtils.isEmpty(providerMap)) {
providerMap.forEach((k, v) -> {
logger.info("[Sentinel Zuul] Register provider name:{}, instance: {}", k,
v);

@ -1,2 +1,3 @@
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.cloud.alibaba.sentinel.zuul.SentinelZuulAutoConfiguration
org.springframework.cloud.alibaba.sentinel.zuul.SentinelZuulAutoConfiguration,\
org.springframework.cloud.alibaba.sentinel.zuul.SentinelSpringCloudGatewayAutoConfiguration

@ -105,6 +105,11 @@
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-api-gateway-adapter-common</artifactId>
</dependency>
<!--spring boot-->
<dependency>

@ -16,23 +16,19 @@
package org.springframework.cloud.alibaba.sentinel.custom;
import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.alibaba.sentinel.SentinelProperties;
import org.springframework.cloud.alibaba.sentinel.datasource.converter.JsonConverter;
import org.springframework.cloud.alibaba.sentinel.datasource.converter.XmlConverter;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import javax.annotation.PostConstruct;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiDefinition;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiPathPredicateItem;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiPredicateGroupItem;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiPredicateItem;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule;
import com.alibaba.csp.sentinel.adapter.servlet.config.WebServletConfig;
import com.alibaba.csp.sentinel.annotation.aspectj.SentinelResourceAspect;
import com.alibaba.csp.sentinel.config.SentinelConfig;
@ -46,9 +42,30 @@ import com.alibaba.csp.sentinel.slots.system.SystemRule;
import com.alibaba.csp.sentinel.transport.config.TransportConfig;
import com.alibaba.csp.sentinel.util.AppNameUtil;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.alibaba.sentinel.SentinelProperties;
import org.springframework.cloud.alibaba.sentinel.datasource.converter.JsonConverter;
import org.springframework.cloud.alibaba.sentinel.datasource.converter.XmlConverter;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
/**
* @author xiaojing
@ -60,173 +77,257 @@ import com.fasterxml.jackson.dataformat.xml.XmlMapper;
@EnableConfigurationProperties(SentinelProperties.class)
public class SentinelAutoConfiguration {
@Value("${project.name:${spring.application.name:}}")
private String projectName;
@Autowired
private SentinelProperties properties;
@PostConstruct
private void init() {
if (StringUtils.isEmpty(System.getProperty(LogBase.LOG_DIR))
&& StringUtils.hasText(properties.getLog().getDir())) {
System.setProperty(LogBase.LOG_DIR, properties.getLog().getDir());
}
if (StringUtils.isEmpty(System.getProperty(LogBase.LOG_NAME_USE_PID))
&& properties.getLog().isSwitchPid()) {
System.setProperty(LogBase.LOG_NAME_USE_PID,
String.valueOf(properties.getLog().isSwitchPid()));
}
if (StringUtils.isEmpty(System.getProperty(AppNameUtil.APP_NAME))
&& StringUtils.hasText(projectName)) {
System.setProperty(AppNameUtil.APP_NAME, projectName);
}
if (StringUtils.isEmpty(System.getProperty(TransportConfig.SERVER_PORT))
&& StringUtils.hasText(properties.getTransport().getPort())) {
System.setProperty(TransportConfig.SERVER_PORT,
properties.getTransport().getPort());
}
if (StringUtils.isEmpty(System.getProperty(TransportConfig.CONSOLE_SERVER))
&& StringUtils.hasText(properties.getTransport().getDashboard())) {
System.setProperty(TransportConfig.CONSOLE_SERVER,
properties.getTransport().getDashboard());
}
if (StringUtils.isEmpty(System.getProperty(TransportConfig.HEARTBEAT_INTERVAL_MS))
&& StringUtils
.hasText(properties.getTransport().getHeartbeatIntervalMs())) {
System.setProperty(TransportConfig.HEARTBEAT_INTERVAL_MS,
properties.getTransport().getHeartbeatIntervalMs());
}
if (StringUtils.isEmpty(System.getProperty(TransportConfig.HEARTBEAT_CLIENT_IP))
&& StringUtils.hasText(properties.getTransport().getClientIp())) {
System.setProperty(TransportConfig.HEARTBEAT_CLIENT_IP,
properties.getTransport().getClientIp());
}
if (StringUtils.isEmpty(System.getProperty(SentinelConfig.CHARSET))
&& StringUtils.hasText(properties.getMetric().getCharset())) {
System.setProperty(SentinelConfig.CHARSET,
properties.getMetric().getCharset());
}
if (StringUtils
.isEmpty(System.getProperty(SentinelConfig.SINGLE_METRIC_FILE_SIZE))
&& StringUtils.hasText(properties.getMetric().getFileSingleSize())) {
System.setProperty(SentinelConfig.SINGLE_METRIC_FILE_SIZE,
properties.getMetric().getFileSingleSize());
}
if (StringUtils
.isEmpty(System.getProperty(SentinelConfig.TOTAL_METRIC_FILE_COUNT))
&& StringUtils.hasText(properties.getMetric().getFileTotalCount())) {
System.setProperty(SentinelConfig.TOTAL_METRIC_FILE_COUNT,
properties.getMetric().getFileTotalCount());
}
if (StringUtils.isEmpty(System.getProperty(SentinelConfig.COLD_FACTOR))
&& StringUtils.hasText(properties.getFlow().getColdFactor())) {
System.setProperty(SentinelConfig.COLD_FACTOR,
properties.getFlow().getColdFactor());
}
if (StringUtils.hasText(properties.getServlet().getBlockPage())) {
WebServletConfig.setBlockPage(properties.getServlet().getBlockPage());
}
// earlier initialize
if (properties.isEager()) {
InitExecutor.doInit();
}
}
@Bean
@ConditionalOnMissingBean
public SentinelResourceAspect sentinelResourceAspect() {
return new SentinelResourceAspect();
}
@Bean
@ConditionalOnMissingBean
@ConditionalOnClass(name = "org.springframework.web.client.RestTemplate")
@ConditionalOnProperty(name = "resttemplate.sentinel.enabled", havingValue = "true", matchIfMissing = true)
public SentinelBeanPostProcessor sentinelBeanPostProcessor(
ApplicationContext applicationContext) {
return new SentinelBeanPostProcessor(applicationContext);
}
@Bean
public SentinelDataSourceHandler sentinelDataSourceHandler(
DefaultListableBeanFactory beanFactory) {
return new SentinelDataSourceHandler(beanFactory);
}
@ConditionalOnClass(ObjectMapper.class)
protected static class SentinelConverterConfiguration {
private ObjectMapper objectMapper = new ObjectMapper();
public SentinelConverterConfiguration() {
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
false);
}
@Bean("sentinel-json-flow-converter")
public JsonConverter jsonFlowConverter() {
return new JsonConverter(objectMapper, FlowRule.class);
}
@Bean("sentinel-json-degrade-converter")
public JsonConverter jsonDegradeConverter() {
return new JsonConverter(objectMapper, DegradeRule.class);
}
@Bean("sentinel-json-system-converter")
public JsonConverter jsonSystemConverter() {
return new JsonConverter(objectMapper, SystemRule.class);
}
@Bean("sentinel-json-authority-converter")
public JsonConverter jsonAuthorityConverter() {
return new JsonConverter(objectMapper, AuthorityRule.class);
}
@Bean("sentinel-json-param-flow-converter")
public JsonConverter jsonParamFlowConverter() {
return new JsonConverter(objectMapper, ParamFlowRule.class);
}
}
@ConditionalOnClass(XmlMapper.class)
protected static class SentinelXmlConfiguration {
private XmlMapper xmlMapper = new XmlMapper();
public SentinelXmlConfiguration() {
xmlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
@Bean("sentinel-xml-flow-converter")
public XmlConverter xmlFlowConverter() {
return new XmlConverter(xmlMapper, FlowRule.class);
}
@Bean("sentinel-xml-degrade-converter")
public XmlConverter xmlDegradeConverter() {
return new XmlConverter(xmlMapper, DegradeRule.class);
}
@Bean("sentinel-xml-system-converter")
public XmlConverter xmlSystemConverter() {
return new XmlConverter(xmlMapper, SystemRule.class);
}
@Bean("sentinel-xml-authority-converter")
public XmlConverter xmlAuthorityConverter() {
return new XmlConverter(xmlMapper, AuthorityRule.class);
}
@Bean("sentinel-xml-param-flow-converter")
public XmlConverter xmlParamFlowConverter() {
return new XmlConverter(xmlMapper, ParamFlowRule.class);
}
}
@Value("${project.name:${spring.application.name:}}")
private String projectName;
@Autowired
private SentinelProperties properties;
@PostConstruct
private void init() {
if (StringUtils.isEmpty(System.getProperty(LogBase.LOG_DIR))
&& StringUtils.hasText(properties.getLog().getDir())) {
System.setProperty(LogBase.LOG_DIR, properties.getLog().getDir());
}
if (StringUtils.isEmpty(System.getProperty(LogBase.LOG_NAME_USE_PID))
&& properties.getLog().isSwitchPid()) {
System.setProperty(LogBase.LOG_NAME_USE_PID,
String.valueOf(properties.getLog().isSwitchPid()));
}
if (StringUtils.isEmpty(System.getProperty(AppNameUtil.APP_NAME))
&& StringUtils.hasText(projectName)) {
System.setProperty(AppNameUtil.APP_NAME, projectName);
}
if (StringUtils.isEmpty(System.getProperty(TransportConfig.SERVER_PORT))
&& StringUtils.hasText(properties.getTransport().getPort())) {
System.setProperty(TransportConfig.SERVER_PORT,
properties.getTransport().getPort());
}
if (StringUtils.isEmpty(System.getProperty(TransportConfig.CONSOLE_SERVER))
&& StringUtils.hasText(properties.getTransport().getDashboard())) {
System.setProperty(TransportConfig.CONSOLE_SERVER,
properties.getTransport().getDashboard());
}
if (StringUtils.isEmpty(System.getProperty(TransportConfig.HEARTBEAT_INTERVAL_MS))
&& StringUtils
.hasText(properties.getTransport().getHeartbeatIntervalMs())) {
System.setProperty(TransportConfig.HEARTBEAT_INTERVAL_MS,
properties.getTransport().getHeartbeatIntervalMs());
}
if (StringUtils.isEmpty(System.getProperty(TransportConfig.HEARTBEAT_CLIENT_IP))
&& StringUtils.hasText(properties.getTransport().getClientIp())) {
System.setProperty(TransportConfig.HEARTBEAT_CLIENT_IP,
properties.getTransport().getClientIp());
}
if (StringUtils.isEmpty(System.getProperty(SentinelConfig.CHARSET))
&& StringUtils.hasText(properties.getMetric().getCharset())) {
System.setProperty(SentinelConfig.CHARSET,
properties.getMetric().getCharset());
}
if (StringUtils
.isEmpty(System.getProperty(SentinelConfig.SINGLE_METRIC_FILE_SIZE))
&& StringUtils.hasText(properties.getMetric().getFileSingleSize())) {
System.setProperty(SentinelConfig.SINGLE_METRIC_FILE_SIZE,
properties.getMetric().getFileSingleSize());
}
if (StringUtils
.isEmpty(System.getProperty(SentinelConfig.TOTAL_METRIC_FILE_COUNT))
&& StringUtils.hasText(properties.getMetric().getFileTotalCount())) {
System.setProperty(SentinelConfig.TOTAL_METRIC_FILE_COUNT,
properties.getMetric().getFileTotalCount());
}
if (StringUtils.isEmpty(System.getProperty(SentinelConfig.COLD_FACTOR))
&& StringUtils.hasText(properties.getFlow().getColdFactor())) {
System.setProperty(SentinelConfig.COLD_FACTOR,
properties.getFlow().getColdFactor());
}
if (StringUtils.hasText(properties.getServlet().getBlockPage())) {
WebServletConfig.setBlockPage(properties.getServlet().getBlockPage());
}
// earlier initialize
if (properties.isEager()) {
InitExecutor.doInit();
}
}
@Bean
@ConditionalOnMissingBean
public SentinelResourceAspect sentinelResourceAspect() {
return new SentinelResourceAspect();
}
@Bean
@ConditionalOnMissingBean
@ConditionalOnClass(name = "org.springframework.web.client.RestTemplate")
@ConditionalOnProperty(name = "resttemplate.sentinel.enabled", havingValue = "true", matchIfMissing = true)
public SentinelBeanPostProcessor sentinelBeanPostProcessor(
ApplicationContext applicationContext) {
return new SentinelBeanPostProcessor(applicationContext);
}
@Bean
public SentinelDataSourceHandler sentinelDataSourceHandler(
DefaultListableBeanFactory beanFactory) {
return new SentinelDataSourceHandler(beanFactory);
}
@ConditionalOnClass(ObjectMapper.class)
@Configuration
protected static class SentinelConverterConfiguration {
static class ApiPredicateItemDeserializer
extends StdDeserializer<ApiPredicateItem> {
private Map<String, Class<? extends ApiPredicateItem>> registry
= new HashMap<String, Class<? extends ApiPredicateItem>>();
ApiPredicateItemDeserializer() {
super(ApiPredicateItem.class);
}
void registerApiPredicateItem(String uniqueAttribute,
Class<? extends ApiPredicateItem> apiPredicateItemClass) {
registry.put(uniqueAttribute, apiPredicateItemClass);
}
@Override
public ApiPredicateItem deserialize(JsonParser jp,
DeserializationContext ctxt)
throws IOException {
ObjectMapper mapper = (ObjectMapper)jp.getCodec();
ObjectNode root = mapper.readTree(jp);
Class<? extends ApiPredicateItem> apiPredicateItemClass = null;
Iterator<Entry<String, JsonNode>> elementsIterator = root.fields();
while (elementsIterator.hasNext()) {
Entry<String, JsonNode> element = elementsIterator.next();
String name = element.getKey();
if (registry.containsKey(name)) {
apiPredicateItemClass = registry.get(name);
break;
}
}
if (apiPredicateItemClass == null) {
return null;
}
return mapper.readValue(root.toString(), apiPredicateItemClass);
}
}
@Configuration
protected static class SentinelJsonConfiguration {
private ObjectMapper objectMapper = new ObjectMapper();
public SentinelJsonConfiguration() {
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
false);
ApiPredicateItemDeserializer deserializer = new ApiPredicateItemDeserializer();
deserializer.registerApiPredicateItem("pattern",
ApiPathPredicateItem.class);
deserializer.registerApiPredicateItem("items",
ApiPredicateGroupItem.class);
SimpleModule module = new SimpleModule(
"PolymorphicApiPredicateItemDeserializerModule",
new Version(1, 0, 0, null));
module.addDeserializer(ApiPredicateItem.class, deserializer);
objectMapper.registerModule(module);
}
@Bean("sentinel-json-flow-converter")
public JsonConverter jsonFlowConverter() {
return new JsonConverter(objectMapper, FlowRule.class);
}
@Bean("sentinel-json-degrade-converter")
public JsonConverter jsonDegradeConverter() {
return new JsonConverter(objectMapper, DegradeRule.class);
}
@Bean("sentinel-json-system-converter")
public JsonConverter jsonSystemConverter() {
return new JsonConverter(objectMapper, SystemRule.class);
}
@Bean("sentinel-json-authority-converter")
public JsonConverter jsonAuthorityConverter() {
return new JsonConverter(objectMapper, AuthorityRule.class);
}
@Bean("sentinel-json-param-flow-converter")
public JsonConverter jsonParamFlowConverter() {
return new JsonConverter(objectMapper, ParamFlowRule.class);
}
@Bean("sentinel-json-gateway-flow-converter")
public JsonConverter jsonGatewayFlowConverter() {
return new JsonConverter(objectMapper, GatewayFlowRule.class);
}
@Bean("sentinel-json-api-converter")
public JsonConverter jsonApiConverter() {
return new JsonConverter(objectMapper, ApiDefinition.class);
}
}
@ConditionalOnClass(XmlMapper.class)
@Configuration
protected static class SentinelXmlConfiguration {
private XmlMapper xmlMapper = new XmlMapper();
public SentinelXmlConfiguration() {
xmlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
false);
ApiPredicateItemDeserializer deserializer = new ApiPredicateItemDeserializer();
deserializer.registerApiPredicateItem("pattern",
ApiPathPredicateItem.class);
deserializer.registerApiPredicateItem("items",
ApiPredicateGroupItem.class);
SimpleModule module = new SimpleModule(
"PolymorphicGatewayDeserializerModule",
new Version(1, 0, 0, null));
module.addDeserializer(ApiPredicateItem.class, deserializer);
xmlMapper.registerModule(module);
}
@Bean("sentinel-xml-flow-converter")
public XmlConverter xmlFlowConverter() {
return new XmlConverter(xmlMapper, FlowRule.class);
}
@Bean("sentinel-xml-degrade-converter")
public XmlConverter xmlDegradeConverter() {
return new XmlConverter(xmlMapper, DegradeRule.class);
}
@Bean("sentinel-xml-system-converter")
public XmlConverter xmlSystemConverter() {
return new XmlConverter(xmlMapper, SystemRule.class);
}
@Bean("sentinel-xml-authority-converter")
public XmlConverter xmlAuthorityConverter() {
return new XmlConverter(xmlMapper, AuthorityRule.class);
}
@Bean("sentinel-xml-param-flow-converter")
public XmlConverter xmlParamFlowConverter() {
return new XmlConverter(xmlMapper, ParamFlowRule.class);
}
@Bean("sentinel-xml-gateway-flow-converter")
public XmlConverter xmlGatewayFlowConverter() {
return new XmlConverter(xmlMapper, GatewayFlowRule.class);
}
@Bean("sentinel-xml-api-converter")
public XmlConverter xmlApiConverter() {
return new XmlConverter(xmlMapper, ApiDefinition.class);
}
}
}
}

@ -1,8 +1,13 @@
package org.springframework.cloud.alibaba.sentinel.custom;
import com.alibaba.csp.sentinel.datasource.AbstractDataSource;
import com.alibaba.csp.sentinel.datasource.ReadableDataSource;
import com.alibaba.csp.sentinel.slots.block.AbstractRule;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -18,12 +23,8 @@ import org.springframework.util.CollectionUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import com.alibaba.csp.sentinel.datasource.AbstractDataSource;
import com.alibaba.csp.sentinel.datasource.ReadableDataSource;
/**
* Sentinel {@link ReadableDataSource} Handler Handle the configurations of
@ -189,7 +190,7 @@ public class SentinelDataSourceHandler implements SmartInitializingSingleton {
}
private void logAndCheckRuleType(AbstractDataSource dataSource, String dataSourceName,
Class<? extends AbstractRule> ruleClass) {
Class ruleClass) {
Object ruleConfig;
try {
ruleConfig = dataSource.loadConfig();
@ -199,8 +200,8 @@ public class SentinelDataSourceHandler implements SmartInitializingSingleton {
+ " loadConfig error: " + e.getMessage(), e);
return;
}
if (ruleConfig instanceof List) {
List convertedRuleList = (List) ruleConfig;
if (ruleConfig instanceof List || ruleConfig instanceof Set) {
Collection convertedRuleList = (Collection) ruleConfig;
if (CollectionUtils.isEmpty(convertedRuleList)) {
log.warn("[Sentinel Starter] DataSource {} rule list is empty.",
dataSourceName);

Loading…
Cancel
Save