mirror of
https://gitee.com/mirrors/Spring-Cloud-Alibaba.git
synced 2021-06-26 13:25:11 +08:00
sync sentinel to 1.x branch
This commit is contained in:
@@ -52,6 +52,12 @@
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-commons</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.alibaba.csp</groupId>
|
||||
<artifactId>sentinel-parameter-flow-control</artifactId>
|
||||
|
||||
@@ -23,7 +23,10 @@ public interface SentinelConstants {
|
||||
|
||||
String PROPERTY_PREFIX = "spring.cloud.sentinel";
|
||||
|
||||
// commercialized
|
||||
String BLOCK_TYPE = "block";
|
||||
String FALLBACK_TYPE = "fallback";
|
||||
|
||||
// commercialization
|
||||
|
||||
String FLOW_DATASOURCE_NAME = "edas-flow";
|
||||
String DEGRADE_DATASOURCE_NAME = "edas-degrade";
|
||||
|
||||
@@ -21,76 +21,72 @@ import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.boot.context.properties.NestedConfigurationProperty;
|
||||
import org.springframework.cloud.alibaba.sentinel.datasource.config.DataSourcePropertiesConfiguration;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
|
||||
import com.alibaba.csp.sentinel.config.SentinelConfig;
|
||||
import com.alibaba.csp.sentinel.log.LogBase;
|
||||
import com.alibaba.csp.sentinel.transport.config.TransportConfig;
|
||||
|
||||
/**
|
||||
* {@link ConfigurationProperties} for Sentinel.
|
||||
*
|
||||
* @author xiaojing
|
||||
* @author hengyunabc
|
||||
* @author jiashuai.xie
|
||||
* @author <a href="mailto:fangjian0423@gmail.com">Jim</a>
|
||||
*/
|
||||
@ConfigurationProperties(prefix = SentinelConstants.PROPERTY_PREFIX)
|
||||
@Validated
|
||||
public class SentinelProperties {
|
||||
|
||||
/**
|
||||
* earlier initialize heart-beat when the spring container starts <note> when the
|
||||
* transport dependency is on classpath ,the configuration is effective </note>
|
||||
* Earlier initialize heart-beat when the spring container starts when the transport
|
||||
* dependency is on classpath, the configuration is effective.
|
||||
*/
|
||||
private boolean eager = false;
|
||||
|
||||
/**
|
||||
* enable sentinel auto configure, the default value is true
|
||||
* Enable sentinel auto configure, the default value is true.
|
||||
*/
|
||||
private boolean enabled = true;
|
||||
|
||||
/**
|
||||
* configurations about datasource, like 'nacos', 'apollo', 'file', 'zookeeper'
|
||||
* Configurations about datasource, like 'nacos', 'apollo', 'file', 'zookeeper'.
|
||||
*/
|
||||
private Map<String, DataSourcePropertiesConfiguration> datasource = new TreeMap<>(
|
||||
String.CASE_INSENSITIVE_ORDER);
|
||||
|
||||
/**
|
||||
* transport configuration about dashboard and client
|
||||
* Transport configuration about dashboard and client.
|
||||
*/
|
||||
@NestedConfigurationProperty
|
||||
private Transport transport = new Transport();
|
||||
|
||||
/**
|
||||
* metric configuration about resource
|
||||
* Metric configuration about resource.
|
||||
*/
|
||||
@NestedConfigurationProperty
|
||||
private Metric metric = new Metric();
|
||||
|
||||
/**
|
||||
* web servlet configuration <note> when the application is web ,the configuration is
|
||||
* effective </note>
|
||||
* Web servlet configuration when the application is web, the configuration is
|
||||
* effective.
|
||||
*/
|
||||
@NestedConfigurationProperty
|
||||
private Servlet servlet = new Servlet();
|
||||
|
||||
/**
|
||||
* sentinel filter <note> when the application is web ,the configuration is effective
|
||||
* </note>
|
||||
* Sentinel filter when the application is web, the configuration is effective.
|
||||
*/
|
||||
@NestedConfigurationProperty
|
||||
private Filter filter = new Filter();
|
||||
|
||||
/**
|
||||
* flow configuration
|
||||
* Sentinel Flow configuration.
|
||||
*/
|
||||
@NestedConfigurationProperty
|
||||
private Flow flow = new Flow();
|
||||
|
||||
/**
|
||||
* sentinel log configuration {@link LogBase}
|
||||
* Sentinel log configuration {@link LogBase}.
|
||||
*/
|
||||
@NestedConfigurationProperty
|
||||
private Log log = new Log();
|
||||
|
||||
public boolean isEager() {
|
||||
@@ -168,7 +164,7 @@ public class SentinelProperties {
|
||||
public static class Flow {
|
||||
|
||||
/**
|
||||
* the cold factor {@link SentinelConfig#COLD_FACTOR}
|
||||
* The cold factor {@link SentinelConfig#COLD_FACTOR}.
|
||||
*/
|
||||
private String coldFactor = "3";
|
||||
|
||||
@@ -185,7 +181,7 @@ public class SentinelProperties {
|
||||
public static class Servlet {
|
||||
|
||||
/**
|
||||
* The process page when the flow control is triggered
|
||||
* The process page when the flow control is triggered.
|
||||
*/
|
||||
private String blockPage;
|
||||
|
||||
@@ -201,17 +197,17 @@ public class SentinelProperties {
|
||||
public static class Metric {
|
||||
|
||||
/**
|
||||
* the metric file size {@link SentinelConfig#SINGLE_METRIC_FILE_SIZE}
|
||||
* The metric file size {@link SentinelConfig#SINGLE_METRIC_FILE_SIZE}.
|
||||
*/
|
||||
private String fileSingleSize;
|
||||
|
||||
/**
|
||||
* the total metric file count {@link SentinelConfig#TOTAL_METRIC_FILE_COUNT}
|
||||
* The total metric file count {@link SentinelConfig#TOTAL_METRIC_FILE_COUNT}.
|
||||
*/
|
||||
private String fileTotalCount;
|
||||
|
||||
/**
|
||||
* charset when sentinel write or search metric file
|
||||
* Charset when sentinel write or search metric file.
|
||||
* {@link SentinelConfig#CHARSET}
|
||||
*/
|
||||
private String charset = "UTF-8";
|
||||
@@ -244,22 +240,28 @@ public class SentinelProperties {
|
||||
public static class Transport {
|
||||
|
||||
/**
|
||||
* sentinel api port,default value is 8719 {@link TransportConfig#SERVER_PORT}
|
||||
* Sentinel api port, default value is 8719 {@link TransportConfig#SERVER_PORT}.
|
||||
*/
|
||||
private String port = "8719";
|
||||
|
||||
/**
|
||||
* sentinel dashboard address, won't try to connect dashboard when address is
|
||||
* empty {@link TransportConfig#CONSOLE_SERVER}
|
||||
* Sentinel dashboard address, won't try to connect dashboard when address is
|
||||
* empty {@link TransportConfig#CONSOLE_SERVER}.
|
||||
*/
|
||||
private String dashboard = "";
|
||||
|
||||
/**
|
||||
* send heartbeat interval millisecond
|
||||
* {@link TransportConfig#HEARTBEAT_INTERVAL_MS}
|
||||
* Send heartbeat interval millisecond
|
||||
* {@link TransportConfig#HEARTBEAT_INTERVAL_MS}.
|
||||
*/
|
||||
private String heartbeatIntervalMs;
|
||||
|
||||
/**
|
||||
* Get heartbeat client local ip. If the client ip not configured, it will be the
|
||||
* address of local host.
|
||||
*/
|
||||
private String clientIp;
|
||||
|
||||
public String getHeartbeatIntervalMs() {
|
||||
return heartbeatIntervalMs;
|
||||
}
|
||||
@@ -284,17 +286,24 @@ public class SentinelProperties {
|
||||
this.dashboard = dashboard;
|
||||
}
|
||||
|
||||
public String getClientIp() {
|
||||
return clientIp;
|
||||
}
|
||||
|
||||
public void setClientIp(String clientIp) {
|
||||
this.clientIp = clientIp;
|
||||
}
|
||||
}
|
||||
|
||||
public static class Filter {
|
||||
|
||||
/**
|
||||
* sentinel filter chain order.
|
||||
* Sentinel filter chain order.
|
||||
*/
|
||||
private int order = Ordered.HIGHEST_PRECEDENCE;
|
||||
|
||||
/**
|
||||
* URL pattern for sentinel filter,default is /*
|
||||
* URL pattern for sentinel filter, default is /*
|
||||
*/
|
||||
private List<String> urlPatterns;
|
||||
|
||||
@@ -318,12 +327,12 @@ public class SentinelProperties {
|
||||
public static class Log {
|
||||
|
||||
/**
|
||||
* sentinel log base dir
|
||||
* Sentinel log base dir.
|
||||
*/
|
||||
private String dir;
|
||||
|
||||
/**
|
||||
* distinguish the log file by pid number
|
||||
* Distinguish the log file by pid number.
|
||||
*/
|
||||
private boolean switchPid = false;
|
||||
|
||||
|
||||
@@ -21,8 +21,6 @@ import java.util.List;
|
||||
|
||||
import javax.servlet.Filter;
|
||||
|
||||
import com.alibaba.csp.sentinel.adapter.servlet.CommonFilter;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
@@ -33,6 +31,8 @@ import org.springframework.boot.web.servlet.FilterRegistrationBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import com.alibaba.csp.sentinel.adapter.servlet.CommonFilter;
|
||||
|
||||
/**
|
||||
* @author xiaojing
|
||||
*/
|
||||
@@ -42,38 +42,33 @@ import org.springframework.context.annotation.Configuration;
|
||||
@EnableConfigurationProperties(SentinelProperties.class)
|
||||
public class SentinelWebAutoConfiguration {
|
||||
|
||||
private static final Logger logger = LoggerFactory
|
||||
.getLogger(SentinelWebAutoConfiguration.class);
|
||||
private static final Logger logger = LoggerFactory
|
||||
.getLogger(SentinelWebAutoConfiguration.class);
|
||||
|
||||
@Autowired
|
||||
private SentinelProperties properties;
|
||||
@Autowired
|
||||
private SentinelProperties properties;
|
||||
|
||||
@Bean
|
||||
public FilterRegistrationBean servletRequestListener() {
|
||||
FilterRegistrationBean registration = new FilterRegistrationBean();
|
||||
@Bean
|
||||
public FilterRegistrationBean servletRequestListener() {
|
||||
FilterRegistrationBean registration = new FilterRegistrationBean();
|
||||
|
||||
SentinelProperties.Filter filterConfig = properties.getFilter();
|
||||
SentinelProperties.Filter filterConfig = properties.getFilter();
|
||||
|
||||
if (null == filterConfig) {
|
||||
filterConfig = new SentinelProperties.Filter();
|
||||
properties.setFilter(filterConfig);
|
||||
}
|
||||
if (filterConfig.getUrlPatterns() == null
|
||||
|| filterConfig.getUrlPatterns().isEmpty()) {
|
||||
List<String> defaultPatterns = new ArrayList<>();
|
||||
defaultPatterns.add("/*");
|
||||
filterConfig.setUrlPatterns(defaultPatterns);
|
||||
}
|
||||
|
||||
if (filterConfig.getUrlPatterns() == null
|
||||
|| filterConfig.getUrlPatterns().isEmpty()) {
|
||||
List<String> defaultPatterns = new ArrayList<>();
|
||||
defaultPatterns.add("/*");
|
||||
filterConfig.setUrlPatterns(defaultPatterns);
|
||||
}
|
||||
registration.addUrlPatterns(filterConfig.getUrlPatterns().toArray(new String[0]));
|
||||
Filter filter = new CommonFilter();
|
||||
registration.setFilter(filter);
|
||||
registration.setOrder(filterConfig.getOrder());
|
||||
logger.info("[Sentinel Starter] register Sentinel with urlPatterns: {}.",
|
||||
filterConfig.getUrlPatterns());
|
||||
return registration;
|
||||
|
||||
registration.addUrlPatterns(filterConfig.getUrlPatterns().toArray(new String[0]));
|
||||
Filter filter = new CommonFilter();
|
||||
registration.setFilter(filter);
|
||||
registration.setOrder(filterConfig.getOrder());
|
||||
logger.info("[Sentinel Starter] register Sentinel with urlPatterns: {}.",
|
||||
filterConfig.getUrlPatterns());
|
||||
return registration;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -27,33 +27,33 @@ import com.alibaba.csp.sentinel.util.StringUtil;
|
||||
*/
|
||||
final class BlockClassRegistry {
|
||||
|
||||
private static final Map<String, Method> FALLBACK_MAP = new ConcurrentHashMap<>();
|
||||
private static final Map<String, Method> BLOCK_HANDLER_MAP = new ConcurrentHashMap<>();
|
||||
private static final Map<String, Method> FALLBACK_MAP = new ConcurrentHashMap<>();
|
||||
private static final Map<String, Method> BLOCK_HANDLER_MAP = new ConcurrentHashMap<>();
|
||||
|
||||
static Method lookupFallback(Class<?> clazz, String name) {
|
||||
return FALLBACK_MAP.get(getKey(clazz, name));
|
||||
}
|
||||
static Method lookupFallback(Class<?> clazz, String name) {
|
||||
return FALLBACK_MAP.get(getKey(clazz, name));
|
||||
}
|
||||
|
||||
static Method lookupBlockHandler(Class<?> clazz, String name) {
|
||||
return BLOCK_HANDLER_MAP.get(getKey(clazz, name));
|
||||
}
|
||||
static Method lookupBlockHandler(Class<?> clazz, String name) {
|
||||
return BLOCK_HANDLER_MAP.get(getKey(clazz, name));
|
||||
}
|
||||
|
||||
static void updateFallbackFor(Class<?> clazz, String name, Method method) {
|
||||
if (clazz == null || StringUtil.isBlank(name)) {
|
||||
throw new IllegalArgumentException("Bad argument");
|
||||
}
|
||||
FALLBACK_MAP.put(getKey(clazz, name), method);
|
||||
}
|
||||
static void updateFallbackFor(Class<?> clazz, String name, Method method) {
|
||||
if (clazz == null || StringUtil.isBlank(name)) {
|
||||
throw new IllegalArgumentException("Bad argument");
|
||||
}
|
||||
FALLBACK_MAP.put(getKey(clazz, name), method);
|
||||
}
|
||||
|
||||
static void updateBlockHandlerFor(Class<?> clazz, String name, Method method) {
|
||||
if (clazz == null || StringUtil.isBlank(name)) {
|
||||
throw new IllegalArgumentException("Bad argument");
|
||||
}
|
||||
BLOCK_HANDLER_MAP.put(getKey(clazz, name), method);
|
||||
}
|
||||
static void updateBlockHandlerFor(Class<?> clazz, String name, Method method) {
|
||||
if (clazz == null || StringUtil.isBlank(name)) {
|
||||
throw new IllegalArgumentException("Bad argument");
|
||||
}
|
||||
BLOCK_HANDLER_MAP.put(getKey(clazz, name), method);
|
||||
}
|
||||
|
||||
private static String getKey(Class<?> clazz, String name) {
|
||||
return String.format("%s:%s", clazz.getCanonicalName(), name);
|
||||
}
|
||||
private static String getKey(Class<?> clazz, String name) {
|
||||
return String.format("%s:%s", clazz.getCanonicalName(), name);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ import javax.annotation.PostConstruct;
|
||||
|
||||
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;
|
||||
@@ -27,10 +28,12 @@ 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 com.alibaba.csp.sentinel.adapter.servlet.callback.RequestOriginParser;
|
||||
import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
|
||||
import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlCleaner;
|
||||
import com.alibaba.csp.sentinel.adapter.servlet.callback.WebCallbackManager;
|
||||
@@ -39,6 +42,11 @@ import com.alibaba.csp.sentinel.annotation.aspectj.SentinelResourceAspect;
|
||||
import com.alibaba.csp.sentinel.config.SentinelConfig;
|
||||
import com.alibaba.csp.sentinel.init.InitExecutor;
|
||||
import com.alibaba.csp.sentinel.log.LogBase;
|
||||
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.flow.FlowRule;
|
||||
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule;
|
||||
import com.alibaba.csp.sentinel.slots.system.SystemRule;
|
||||
import com.alibaba.csp.sentinel.transport.config.TransportConfig;
|
||||
import com.alibaba.csp.sentinel.util.AppNameUtil;
|
||||
|
||||
@@ -47,6 +55,7 @@ import com.fasterxml.jackson.dataformat.xml.XmlMapper;
|
||||
|
||||
/**
|
||||
* @author xiaojing
|
||||
* @author jiashuai.xie
|
||||
* @author <a href="mailto:fangjian0423@gmail.com">Jim</a>
|
||||
*/
|
||||
@Configuration
|
||||
@@ -66,8 +75,20 @@ public class SentinelAutoConfiguration {
|
||||
@Autowired(required = false)
|
||||
private UrlBlockHandler urlBlockHandler;
|
||||
|
||||
@Autowired(required = false)
|
||||
private RequestOriginParser requestOriginParser;
|
||||
|
||||
@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);
|
||||
@@ -88,6 +109,11 @@ public class SentinelAutoConfiguration {
|
||||
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,
|
||||
@@ -110,30 +136,25 @@ public class SentinelAutoConfiguration {
|
||||
System.setProperty(SentinelConfig.COLD_FACTOR,
|
||||
properties.getFlow().getColdFactor());
|
||||
}
|
||||
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.hasText(properties.getServlet().getBlockPage())) {
|
||||
WebServletConfig.setBlockPage(properties.getServlet().getBlockPage());
|
||||
}
|
||||
|
||||
if (urlBlockHandler != null) {
|
||||
WebCallbackManager.setUrlBlockHandler(urlBlockHandler);
|
||||
}
|
||||
if (urlCleaner != null) {
|
||||
WebCallbackManager.setUrlCleaner(urlCleaner);
|
||||
}
|
||||
if (requestOriginParser != null) {
|
||||
WebCallbackManager.setRequestOriginParser(requestOriginParser);
|
||||
}
|
||||
|
||||
// earlier initialize
|
||||
if (properties.isEager()) {
|
||||
InitExecutor.doInit();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Bean
|
||||
@@ -145,34 +166,78 @@ public class SentinelAutoConfiguration {
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
@ConditionalOnClass(name = "org.springframework.web.client.RestTemplate")
|
||||
public SentinelBeanPostProcessor sentinelBeanPostProcessor() {
|
||||
return new SentinelBeanPostProcessor();
|
||||
public SentinelBeanPostProcessor sentinelBeanPostProcessor(
|
||||
ApplicationContext applicationContext) {
|
||||
return new SentinelBeanPostProcessor(applicationContext);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SentinelDataSourceHandler sentinelDataSourceHandler() {
|
||||
return new SentinelDataSourceHandler();
|
||||
public SentinelDataSourceHandler sentinelDataSourceHandler(
|
||||
DefaultListableBeanFactory beanFactory) {
|
||||
return new SentinelDataSourceHandler(beanFactory);
|
||||
}
|
||||
|
||||
@Bean("sentinel-json-converter")
|
||||
public JsonConverter jsonConverter() {
|
||||
return new JsonConverter(objectMapper());
|
||||
}
|
||||
protected static class SentinelConverterConfiguration {
|
||||
|
||||
private ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
@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);
|
||||
}
|
||||
|
||||
private ObjectMapper objectMapper() {
|
||||
return new ObjectMapper();
|
||||
}
|
||||
|
||||
@ConditionalOnClass(XmlMapper.class)
|
||||
protected static class SentinelXmlConfiguration {
|
||||
@Bean("sentinel-xml-converter")
|
||||
public XmlConverter xmlConverter() {
|
||||
return new XmlConverter(xmlMapper());
|
||||
|
||||
private XmlMapper xmlMapper = new XmlMapper();
|
||||
|
||||
@Bean("sentinel-xml-flow-converter")
|
||||
public XmlConverter xmlFlowConverter() {
|
||||
return new XmlConverter(xmlMapper, FlowRule.class);
|
||||
}
|
||||
|
||||
private XmlMapper xmlMapper() {
|
||||
return new XmlMapper();
|
||||
@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);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -16,21 +16,34 @@
|
||||
|
||||
package org.springframework.cloud.alibaba.sentinel.custom;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.config.BeanDefinition;
|
||||
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
|
||||
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
|
||||
import org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor;
|
||||
import org.springframework.beans.factory.support.RootBeanDefinition;
|
||||
import org.springframework.cloud.alibaba.sentinel.SentinelConstants;
|
||||
import org.springframework.cloud.alibaba.sentinel.annotation.SentinelRestTemplate;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.core.type.StandardMethodMetadata;
|
||||
import org.springframework.core.type.classreading.MethodMetadataReadingVisitor;
|
||||
import org.springframework.http.HttpRequest;
|
||||
import org.springframework.http.client.ClientHttpRequestExecution;
|
||||
import org.springframework.http.client.ClientHttpResponse;
|
||||
import org.springframework.util.ClassUtils;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import com.alibaba.csp.sentinel.slots.block.BlockException;
|
||||
|
||||
/**
|
||||
* PostProcessor handle @SentinelRestTemplate Annotation, add interceptor for RestTemplate
|
||||
*
|
||||
@@ -40,8 +53,14 @@ import org.springframework.web.client.RestTemplate;
|
||||
*/
|
||||
public class SentinelBeanPostProcessor implements MergedBeanDefinitionPostProcessor {
|
||||
|
||||
@Autowired
|
||||
private ApplicationContext applicationContext;
|
||||
private static final Logger logger = LoggerFactory
|
||||
.getLogger(SentinelBeanPostProcessor.class);
|
||||
|
||||
private final ApplicationContext applicationContext;
|
||||
|
||||
public SentinelBeanPostProcessor(ApplicationContext applicationContext) {
|
||||
this.applicationContext = applicationContext;
|
||||
}
|
||||
|
||||
private ConcurrentHashMap<String, SentinelRestTemplate> cache = new ConcurrentHashMap<>();
|
||||
|
||||
@@ -49,21 +68,113 @@ public class SentinelBeanPostProcessor implements MergedBeanDefinitionPostProces
|
||||
public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition,
|
||||
Class<?> beanType, String beanName) {
|
||||
if (checkSentinelProtect(beanDefinition, beanType)) {
|
||||
SentinelRestTemplate sentinelRestTemplate = ((StandardMethodMetadata) beanDefinition
|
||||
.getSource()).getIntrospectedMethod()
|
||||
.getAnnotation(SentinelRestTemplate.class);
|
||||
SentinelRestTemplate sentinelRestTemplate;
|
||||
if (beanDefinition.getSource() instanceof StandardMethodMetadata) {
|
||||
sentinelRestTemplate = ((StandardMethodMetadata) beanDefinition
|
||||
.getSource()).getIntrospectedMethod()
|
||||
.getAnnotation(SentinelRestTemplate.class);
|
||||
}
|
||||
else {
|
||||
sentinelRestTemplate = beanDefinition.getResolvedFactoryMethod()
|
||||
.getAnnotation(SentinelRestTemplate.class);
|
||||
}
|
||||
// check class and method validation
|
||||
checkSentinelRestTemplate(sentinelRestTemplate, beanName);
|
||||
cache.put(beanName, sentinelRestTemplate);
|
||||
}
|
||||
}
|
||||
|
||||
private void checkSentinelRestTemplate(SentinelRestTemplate sentinelRestTemplate,
|
||||
String beanName) {
|
||||
checkBlock4RestTemplate(sentinelRestTemplate.blockHandlerClass(),
|
||||
sentinelRestTemplate.blockHandler(), beanName,
|
||||
SentinelConstants.BLOCK_TYPE);
|
||||
checkBlock4RestTemplate(sentinelRestTemplate.fallbackClass(),
|
||||
sentinelRestTemplate.fallback(), beanName,
|
||||
SentinelConstants.FALLBACK_TYPE);
|
||||
}
|
||||
|
||||
private void checkBlock4RestTemplate(Class<?> blockClass, String blockMethod,
|
||||
String beanName, String type) {
|
||||
if (blockClass == void.class && StringUtils.isEmpty(blockMethod)) {
|
||||
return;
|
||||
}
|
||||
if (blockClass != void.class && StringUtils.isEmpty(blockMethod)) {
|
||||
logger.error(
|
||||
"{} class attribute exists but {} method attribute is not exists in bean[{}]",
|
||||
type, type, beanName);
|
||||
throw new IllegalArgumentException(type + " class attribute exists but "
|
||||
+ type + " method attribute is not exists in bean[" + beanName + "]");
|
||||
}
|
||||
else if (blockClass == void.class && !StringUtils.isEmpty(blockMethod)) {
|
||||
logger.error(
|
||||
"{} method attribute exists but {} class attribute is not exists in bean[{}]",
|
||||
type, type, beanName);
|
||||
throw new IllegalArgumentException(type + " method attribute exists but "
|
||||
+ type + " class attribute is not exists in bean[" + beanName + "]");
|
||||
}
|
||||
Class[] args = new Class[] { HttpRequest.class, byte[].class,
|
||||
ClientHttpRequestExecution.class, BlockException.class };
|
||||
|
||||
List<String> argList = new ArrayList<>();
|
||||
for (Class argClazz : args) {
|
||||
argList.add(argClazz.getSimpleName());
|
||||
}
|
||||
String argsStr = Arrays.toString(argList.toArray());
|
||||
Method foundMethod = ClassUtils.getStaticMethod(blockClass, blockMethod, args);
|
||||
if (foundMethod == null) {
|
||||
logger.error(
|
||||
"{} static method can not be found in bean[{}]. The right method signature is {}#{}{}, please check your class name, method name and arguments",
|
||||
type, beanName, blockClass.getName(), blockMethod, argsStr);
|
||||
throw new IllegalArgumentException(type
|
||||
+ " static method can not be found in bean[" + beanName
|
||||
+ "]. The right method signature is " + blockClass.getName() + "#"
|
||||
+ blockMethod + argsStr
|
||||
+ ", please check your class name, method name and arguments");
|
||||
}
|
||||
|
||||
if (!ClientHttpResponse.class.isAssignableFrom(foundMethod.getReturnType())) {
|
||||
logger.error(
|
||||
"{} method return value in bean[{}] is not ClientHttpResponse: {}#{}{}",
|
||||
type, beanName, blockClass.getName(), blockMethod, argsStr);
|
||||
throw new IllegalArgumentException(type + " method return value in bean["
|
||||
+ beanName + "] is not ClientHttpResponse: " + blockClass.getName()
|
||||
+ "#" + blockMethod + argsStr);
|
||||
}
|
||||
if (type.equals(SentinelConstants.BLOCK_TYPE)) {
|
||||
BlockClassRegistry.updateBlockHandlerFor(blockClass, blockMethod,
|
||||
foundMethod);
|
||||
}
|
||||
else {
|
||||
BlockClassRegistry.updateFallbackFor(blockClass, blockMethod, foundMethod);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean checkSentinelProtect(RootBeanDefinition beanDefinition,
|
||||
Class<?> beanType) {
|
||||
return beanType == RestTemplate.class
|
||||
&& beanDefinition.getSource() instanceof StandardMethodMetadata
|
||||
&& (checkStandardMethodMetadata(beanDefinition)
|
||||
|| checkMethodMetadataReadingVisitor(beanDefinition));
|
||||
}
|
||||
|
||||
private boolean checkStandardMethodMetadata(RootBeanDefinition beanDefinition) {
|
||||
return beanDefinition.getSource() instanceof StandardMethodMetadata
|
||||
&& ((StandardMethodMetadata) beanDefinition.getSource())
|
||||
.isAnnotated(SentinelRestTemplate.class.getName());
|
||||
}
|
||||
|
||||
private boolean checkMethodMetadataReadingVisitor(RootBeanDefinition beanDefinition) {
|
||||
return beanDefinition.getSource() instanceof MethodMetadataReadingVisitor
|
||||
&& ((MethodMetadataReadingVisitor) beanDefinition.getSource())
|
||||
.isAnnotated(SentinelRestTemplate.class.getName());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object postProcessBeforeInitialization(Object o, String s)
|
||||
throws BeansException {
|
||||
return o;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object postProcessAfterInitialization(Object bean, String beanName)
|
||||
throws BeansException {
|
||||
@@ -84,7 +195,7 @@ public class SentinelBeanPostProcessor implements MergedBeanDefinitionPostProces
|
||||
SentinelProtectInterceptor sentinelProtectInterceptor = applicationContext
|
||||
.getBean(interceptorBeanName.toString(),
|
||||
SentinelProtectInterceptor.class);
|
||||
restTemplate.getInterceptors().add(sentinelProtectInterceptor);
|
||||
restTemplate.getInterceptors().add(0, sentinelProtectInterceptor);
|
||||
}
|
||||
return bean;
|
||||
}
|
||||
@@ -103,10 +214,4 @@ public class SentinelBeanPostProcessor implements MergedBeanDefinitionPostProces
|
||||
interceptorBeanDefinition);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object postProcessBeforeInitialization(Object bean, String beanName)
|
||||
throws BeansException {
|
||||
return bean;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
/*
|
||||
* 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
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.cloud.alibaba.sentinel.custom;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* @author lengleng
|
||||
* <p>
|
||||
* support @EnableCircuitBreaker ,Do nothing
|
||||
*/
|
||||
@Configuration
|
||||
public class SentinelCircuitBreakerConfiguration {
|
||||
}
|
||||
@@ -17,47 +17,29 @@
|
||||
package org.springframework.cloud.alibaba.sentinel.custom;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.SmartInitializingSingleton;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
|
||||
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
|
||||
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||
import org.springframework.cloud.alibaba.sentinel.SentinelConstants;
|
||||
import org.springframework.cloud.alibaba.sentinel.SentinelProperties;
|
||||
import org.springframework.cloud.alibaba.sentinel.datasource.SentinelDataSourceConstants;
|
||||
import org.springframework.cloud.alibaba.sentinel.datasource.config.AbstractDataSourceProperties;
|
||||
import org.springframework.cloud.alibaba.sentinel.datasource.config.DataSourcePropertiesConfiguration;
|
||||
import org.springframework.cloud.alibaba.sentinel.datasource.config.NacosDataSourceProperties;
|
||||
import org.springframework.cloud.alibaba.sentinel.datasource.converter.JsonConverter;
|
||||
import org.springframework.cloud.alibaba.sentinel.datasource.converter.XmlConverter;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
import org.springframework.util.ReflectionUtils;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import com.alibaba.csp.sentinel.datasource.AbstractDataSource;
|
||||
import com.alibaba.csp.sentinel.datasource.ReadableDataSource;
|
||||
import com.alibaba.csp.sentinel.property.SentinelProperty;
|
||||
import com.alibaba.csp.sentinel.slots.block.AbstractRule;
|
||||
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRule;
|
||||
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRuleManager;
|
||||
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
|
||||
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
|
||||
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
|
||||
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
|
||||
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule;
|
||||
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRuleManager;
|
||||
import com.alibaba.csp.sentinel.slots.system.SystemRule;
|
||||
import com.alibaba.csp.sentinel.slots.system.SystemRuleManager;
|
||||
|
||||
/**
|
||||
* Sentinel {@link ReadableDataSource} Handler Handle the configurations of
|
||||
@@ -68,113 +50,53 @@ import com.alibaba.csp.sentinel.slots.system.SystemRuleManager;
|
||||
* @see JsonConverter
|
||||
* @see XmlConverter
|
||||
*/
|
||||
public class SentinelDataSourceHandler {
|
||||
public class SentinelDataSourceHandler implements SmartInitializingSingleton {
|
||||
|
||||
private static final Logger logger = LoggerFactory
|
||||
.getLogger(SentinelDataSourceHandler.class);
|
||||
|
||||
private List<String> dataTypeList = Arrays.asList("json", "xml");
|
||||
|
||||
private List<Class<? extends AbstractRule>> rulesList = Arrays.asList(FlowRule.class,
|
||||
DegradeRule.class, SystemRule.class, AuthorityRule.class,
|
||||
ParamFlowRule.class);
|
||||
private final String DATA_TYPE_FIELD = "dataType";
|
||||
private final String CUSTOM_DATA_TYPE = "custom";
|
||||
private final String CONVERTER_CLASS_FIELD = "converterClass";
|
||||
|
||||
private List<String> dataSourceBeanNameList = Collections
|
||||
.synchronizedList(new ArrayList<String>());
|
||||
private final DefaultListableBeanFactory beanFactory;
|
||||
|
||||
private final String DATATYPE_FIELD = "dataType";
|
||||
private final String CUSTOM_DATATYPE = "custom";
|
||||
private final String CONVERTERCLASS_FIELD = "converterClass";
|
||||
public SentinelDataSourceHandler(DefaultListableBeanFactory beanFactory) {
|
||||
this.beanFactory = beanFactory;
|
||||
}
|
||||
|
||||
@Autowired
|
||||
private SentinelProperties sentinelProperties;
|
||||
|
||||
@EventListener(classes = ApplicationReadyEvent.class)
|
||||
public void buildDataSource(ApplicationReadyEvent event) throws Exception {
|
||||
|
||||
DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) event
|
||||
.getApplicationContext().getAutowireCapableBeanFactory();
|
||||
|
||||
// commercialization
|
||||
if (!StringUtils.isEmpty(System.getProperties()
|
||||
.getProperty(SentinelDataSourceConstants.NACOS_DATASOURCE_ENDPOINT))) {
|
||||
Map<String, DataSourcePropertiesConfiguration> newDataSourceMap = new TreeMap<>(
|
||||
String.CASE_INSENSITIVE_ORDER);
|
||||
for (Map.Entry<String, DataSourcePropertiesConfiguration> entry : sentinelProperties
|
||||
.getDatasource().entrySet()) {
|
||||
if (entry.getValue().getValidDataSourceProperties()
|
||||
.getClass() != NacosDataSourceProperties.class) {
|
||||
newDataSourceMap.put(entry.getKey(), entry.getValue());
|
||||
}
|
||||
}
|
||||
newDataSourceMap.put(SentinelConstants.FLOW_DATASOURCE_NAME,
|
||||
new DataSourcePropertiesConfiguration(
|
||||
NacosDataSourceProperties.buildFlowByEDAS()));
|
||||
newDataSourceMap.put(SentinelConstants.DEGRADE_DATASOURCE_NAME,
|
||||
new DataSourcePropertiesConfiguration(
|
||||
NacosDataSourceProperties.buildDegradeByEDAS()));
|
||||
sentinelProperties.setDatasource(newDataSourceMap);
|
||||
}
|
||||
|
||||
for (Map.Entry<String, DataSourcePropertiesConfiguration> entry : sentinelProperties
|
||||
.getDatasource().entrySet()) {
|
||||
String dataSourceName = entry.getKey();
|
||||
DataSourcePropertiesConfiguration dataSourceProperties = entry.getValue();
|
||||
|
||||
List<String> validFields = dataSourceProperties.getValidField();
|
||||
if (validFields.size() != 1) {
|
||||
logger.error("[Sentinel Starter] DataSource " + dataSourceName
|
||||
+ " multi datasource active and won't loaded: "
|
||||
+ dataSourceProperties.getValidField());
|
||||
return;
|
||||
}
|
||||
|
||||
AbstractDataSourceProperties abstractDataSourceProperties = dataSourceProperties
|
||||
.getValidDataSourceProperties();
|
||||
abstractDataSourceProperties.preCheck();
|
||||
registerBean(beanFactory, abstractDataSourceProperties,
|
||||
dataSourceName + "-sentinel-" + validFields.get(0) + "-datasource");
|
||||
|
||||
}
|
||||
|
||||
for (String beanName : dataSourceBeanNameList) {
|
||||
ReadableDataSource dataSource = beanFactory.getBean(beanName,
|
||||
ReadableDataSource.class);
|
||||
Object ruleConfig;
|
||||
@Override
|
||||
public void afterSingletonsInstantiated() {
|
||||
for (String dataSourceName : sentinelProperties.getDatasource().keySet()) {
|
||||
DataSourcePropertiesConfiguration dataSourceProperties = sentinelProperties
|
||||
.getDatasource().get(dataSourceName);
|
||||
try {
|
||||
logger.info("[Sentinel Starter] DataSource " + beanName
|
||||
+ " start to loadConfig");
|
||||
ruleConfig = dataSource.loadConfig();
|
||||
List<String> validFields = dataSourceProperties.getValidField();
|
||||
if (validFields.size() != 1) {
|
||||
logger.error("[Sentinel Starter] DataSource " + dataSourceName
|
||||
+ " multi datasource active and won't loaded: "
|
||||
+ dataSourceProperties.getValidField());
|
||||
return;
|
||||
}
|
||||
AbstractDataSourceProperties abstractDataSourceProperties = dataSourceProperties
|
||||
.getValidDataSourceProperties();
|
||||
abstractDataSourceProperties.preCheck(dataSourceName);
|
||||
registerBean(abstractDataSourceProperties, dataSourceName + "-sentinel-"
|
||||
+ validFields.get(0) + "-datasource");
|
||||
}
|
||||
catch (Exception e) {
|
||||
logger.error("[Sentinel Starter] DataSource " + beanName
|
||||
+ " loadConfig error: " + e.getMessage(), e);
|
||||
return;
|
||||
}
|
||||
SentinelProperty sentinelProperty = dataSource.getProperty();
|
||||
Class ruleType = getAndCheckRuleType(ruleConfig, beanName);
|
||||
if (ruleType != null) {
|
||||
if (ruleType == FlowRule.class) {
|
||||
FlowRuleManager.register2Property(sentinelProperty);
|
||||
}
|
||||
else if (ruleType == DegradeRule.class) {
|
||||
DegradeRuleManager.register2Property(sentinelProperty);
|
||||
}
|
||||
else if (ruleType == SystemRule.class) {
|
||||
SystemRuleManager.register2Property(sentinelProperty);
|
||||
}
|
||||
else if (ruleType == AuthorityRule.class) {
|
||||
AuthorityRuleManager.register2Property(sentinelProperty);
|
||||
}
|
||||
else {
|
||||
ParamFlowRuleManager.register2Property(sentinelProperty);
|
||||
}
|
||||
logger.error("[Sentinel Starter] DataSource " + dataSourceName
|
||||
+ " build error: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void registerBean(DefaultListableBeanFactory beanFactory,
|
||||
final AbstractDataSourceProperties dataSourceProperties,
|
||||
private void registerBean(final AbstractDataSourceProperties dataSourceProperties,
|
||||
String dataSourceName) {
|
||||
|
||||
Map<String, Object> propertyMap = new HashMap<>();
|
||||
@@ -194,8 +116,9 @@ public class SentinelDataSourceHandler {
|
||||
e);
|
||||
}
|
||||
}
|
||||
propertyMap.put(CONVERTERCLASS_FIELD, dataSourceProperties.getConverterClass());
|
||||
propertyMap.put(DATATYPE_FIELD, dataSourceProperties.getDataType());
|
||||
|
||||
propertyMap.put(CONVERTER_CLASS_FIELD, dataSourceProperties.getConverterClass());
|
||||
propertyMap.put(DATA_TYPE_FIELD, dataSourceProperties.getDataType());
|
||||
|
||||
BeanDefinitionBuilder builder = BeanDefinitionBuilder
|
||||
.genericBeanDefinition(dataSourceProperties.getFactoryBeanName());
|
||||
@@ -205,166 +128,136 @@ public class SentinelDataSourceHandler {
|
||||
Object propertyValue = entry.getValue();
|
||||
Field field = ReflectionUtils.findField(dataSourceProperties.getClass(),
|
||||
propertyName);
|
||||
if (field != null) {
|
||||
if (DATATYPE_FIELD.equals(propertyName)) {
|
||||
String dataType = StringUtils
|
||||
.trimAllWhitespace(propertyValue.toString());
|
||||
if (CUSTOM_DATATYPE.equals(dataType)) {
|
||||
try {
|
||||
if (StringUtils
|
||||
.isEmpty(dataSourceProperties.getConverterClass())) {
|
||||
throw new RuntimeException(
|
||||
"[Sentinel Starter] DataSource " + dataSourceName
|
||||
+ "dataType is custom, please set converter-class "
|
||||
+ "property");
|
||||
}
|
||||
// construct custom Converter with 'converterClass'
|
||||
// configuration and register
|
||||
String customConvertBeanName = "sentinel-"
|
||||
+ dataSourceProperties.getConverterClass();
|
||||
if (!beanFactory.containsBean(customConvertBeanName)) {
|
||||
beanFactory.registerBeanDefinition(customConvertBeanName,
|
||||
BeanDefinitionBuilder
|
||||
.genericBeanDefinition(
|
||||
Class.forName(dataSourceProperties
|
||||
.getConverterClass()))
|
||||
.getBeanDefinition());
|
||||
}
|
||||
builder.addPropertyReference("converter",
|
||||
customConvertBeanName);
|
||||
}
|
||||
catch (ClassNotFoundException e) {
|
||||
logger.error("[Sentinel Starter] DataSource " + dataSourceName
|
||||
+ " handle "
|
||||
+ dataSourceProperties.getClass().getSimpleName()
|
||||
+ " error, class name: "
|
||||
+ dataSourceProperties.getConverterClass());
|
||||
throw new RuntimeException(
|
||||
"[Sentinel Starter] DataSource " + dataSourceName
|
||||
+ " handle "
|
||||
+ dataSourceProperties.getClass()
|
||||
.getSimpleName()
|
||||
+ " error, class name: "
|
||||
+ dataSourceProperties.getConverterClass(),
|
||||
e);
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (!dataTypeList.contains(StringUtils
|
||||
.trimAllWhitespace(propertyValue.toString()))) {
|
||||
if (null == field) {
|
||||
continue;
|
||||
}
|
||||
if (DATA_TYPE_FIELD.equals(propertyName)) {
|
||||
String dataType = StringUtils.trimAllWhitespace(propertyValue.toString());
|
||||
if (CUSTOM_DATA_TYPE.equals(dataType)) {
|
||||
try {
|
||||
if (StringUtils
|
||||
.isEmpty(dataSourceProperties.getConverterClass())) {
|
||||
throw new RuntimeException("[Sentinel Starter] DataSource "
|
||||
+ dataSourceName + " dataType: " + propertyValue
|
||||
+ " is not support now. please using these types: "
|
||||
+ dataTypeList.toString());
|
||||
+ dataSourceName
|
||||
+ "dataType is custom, please set converter-class "
|
||||
+ "property");
|
||||
}
|
||||
// converter type now support xml or json.
|
||||
// The bean name of these converters wrapped by
|
||||
// 'sentinel-{converterType}-converter'
|
||||
builder.addPropertyReference("converter",
|
||||
"sentinel-" + propertyValue.toString() + "-converter");
|
||||
// construct custom Converter with 'converterClass'
|
||||
// configuration and register
|
||||
String customConvertBeanName = "sentinel-"
|
||||
+ dataSourceProperties.getConverterClass();
|
||||
if (!this.beanFactory.containsBean(customConvertBeanName)) {
|
||||
this.beanFactory.registerBeanDefinition(customConvertBeanName,
|
||||
BeanDefinitionBuilder
|
||||
.genericBeanDefinition(
|
||||
Class.forName(dataSourceProperties
|
||||
.getConverterClass()))
|
||||
.getBeanDefinition());
|
||||
}
|
||||
builder.addPropertyReference("converter", customConvertBeanName);
|
||||
}
|
||||
catch (ClassNotFoundException e) {
|
||||
logger.error("[Sentinel Starter] DataSource " + dataSourceName
|
||||
+ " handle "
|
||||
+ dataSourceProperties.getClass().getSimpleName()
|
||||
+ " error, class name: "
|
||||
+ dataSourceProperties.getConverterClass());
|
||||
throw new RuntimeException("[Sentinel Starter] DataSource "
|
||||
+ dataSourceName + " handle "
|
||||
+ dataSourceProperties.getClass().getSimpleName()
|
||||
+ " error, class name: "
|
||||
+ dataSourceProperties.getConverterClass(), e);
|
||||
}
|
||||
}
|
||||
else if (CONVERTERCLASS_FIELD.equals(propertyName)) {
|
||||
continue;
|
||||
}
|
||||
else {
|
||||
// wired properties
|
||||
if (propertyValue != null) {
|
||||
builder.addPropertyValue(propertyName, propertyValue);
|
||||
if (!dataTypeList.contains(
|
||||
StringUtils.trimAllWhitespace(propertyValue.toString()))) {
|
||||
throw new RuntimeException("[Sentinel Starter] DataSource "
|
||||
+ dataSourceName + " dataType: " + propertyValue
|
||||
+ " is not support now. please using these types: "
|
||||
+ dataTypeList.toString());
|
||||
}
|
||||
// converter type now support xml or json.
|
||||
// The bean name of these converters wrapped by
|
||||
// 'sentinel-{converterType}-{ruleType}-converter'
|
||||
builder.addPropertyReference("converter",
|
||||
"sentinel-" + propertyValue.toString() + "-"
|
||||
+ dataSourceProperties.getRuleType().getName()
|
||||
+ "-converter");
|
||||
}
|
||||
}
|
||||
else if (CONVERTER_CLASS_FIELD.equals(propertyName)) {
|
||||
continue;
|
||||
}
|
||||
else {
|
||||
// wired properties
|
||||
if (propertyValue != null) {
|
||||
builder.addPropertyValue(propertyName, propertyValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
beanFactory.registerBeanDefinition(dataSourceName, builder.getBeanDefinition());
|
||||
this.beanFactory.registerBeanDefinition(dataSourceName,
|
||||
builder.getBeanDefinition());
|
||||
// init in Spring
|
||||
AbstractDataSource newDataSource = (AbstractDataSource) beanFactory
|
||||
AbstractDataSource newDataSource = (AbstractDataSource) this.beanFactory
|
||||
.getBean(dataSourceName);
|
||||
// commercialization
|
||||
if (!StringUtils.isEmpty(System.getProperties()
|
||||
.getProperty(SentinelDataSourceConstants.NACOS_DATASOURCE_ENDPOINT))) {
|
||||
if (dataSourceName.contains(SentinelConstants.FLOW_DATASOURCE_NAME)) {
|
||||
FlowRuleManager.register2Property(newDataSource.getProperty());
|
||||
}
|
||||
else if (dataSourceName.contains(SentinelConstants.DEGRADE_DATASOURCE_NAME)) {
|
||||
DegradeRuleManager.register2Property(newDataSource.getProperty());
|
||||
}
|
||||
}
|
||||
dataSourceBeanNameList.add(dataSourceName);
|
||||
|
||||
logAndCheckRuleType(newDataSource, dataSourceName,
|
||||
dataSourceProperties.getRuleType().getClazz());
|
||||
|
||||
// register property in RuleManager
|
||||
dataSourceProperties.postRegister(newDataSource);
|
||||
}
|
||||
|
||||
private Class getAndCheckRuleType(Object ruleConfig, String dataSourceName) {
|
||||
if (rulesList.contains(ruleConfig.getClass())) {
|
||||
logger.info("[Sentinel Starter] DataSource {} load {} {}", dataSourceName, 1,
|
||||
ruleConfig.getClass().getSimpleName());
|
||||
return ruleConfig.getClass();
|
||||
private void logAndCheckRuleType(AbstractDataSource dataSource, String dataSourceName,
|
||||
Class<? extends AbstractRule> ruleClass) {
|
||||
Object ruleConfig;
|
||||
try {
|
||||
ruleConfig = dataSource.loadConfig();
|
||||
}
|
||||
else if (ruleConfig instanceof List) {
|
||||
catch (Exception e) {
|
||||
logger.error("[Sentinel Starter] DataSource " + dataSourceName
|
||||
+ " loadConfig error: " + e.getMessage(), e);
|
||||
return;
|
||||
}
|
||||
if (ruleConfig instanceof List) {
|
||||
List convertedRuleList = (List) ruleConfig;
|
||||
if (CollectionUtils.isEmpty(convertedRuleList)) {
|
||||
logger.warn("[Sentinel Starter] DataSource {} rule list is empty.",
|
||||
dataSourceName);
|
||||
return null;
|
||||
return;
|
||||
}
|
||||
|
||||
if (checkRuleTypeValid(convertedRuleList)) {
|
||||
if (checkAllRuleTypeSame(convertedRuleList)) {
|
||||
logger.info("[Sentinel Starter] DataSource {} load {} {}",
|
||||
dataSourceName, convertedRuleList.size(),
|
||||
convertedRuleList.get(0).getClass().getSimpleName());
|
||||
return convertedRuleList.get(0).getClass();
|
||||
}
|
||||
else {
|
||||
logger.warn(
|
||||
"[Sentinel Starter] DataSource {} all rules are not same rule type and it will not be used. "
|
||||
+ "Rule List: {}",
|
||||
dataSourceName, convertedRuleList.toString());
|
||||
int matchCount = 0;
|
||||
for (Object rule : convertedRuleList) {
|
||||
if (rule.getClass() == ruleClass) {
|
||||
matchCount++;
|
||||
}
|
||||
}
|
||||
if (matchCount == 0) {
|
||||
logger.error("[Sentinel Starter] DataSource {} none rules are {} type.",
|
||||
dataSourceName, ruleClass.getSimpleName());
|
||||
throw new IllegalArgumentException("[Sentinel Starter] DataSource "
|
||||
+ dataSourceName + " none rules are " + ruleClass.getSimpleName()
|
||||
+ " type.");
|
||||
}
|
||||
else if (matchCount != convertedRuleList.size()) {
|
||||
logger.warn("[Sentinel Starter] DataSource {} all rules are not {} type.",
|
||||
dataSourceName, ruleClass.getSimpleName());
|
||||
}
|
||||
else {
|
||||
List<Class> classList = new ArrayList<>();
|
||||
for (Object rule : convertedRuleList) {
|
||||
classList.add(rule.getClass());
|
||||
}
|
||||
logger.error("[Sentinel Starter] DataSource " + dataSourceName
|
||||
+ " rule class is invalid. Class List: " + classList);
|
||||
throw new RuntimeException(
|
||||
"[Sentinel Starter] DataSource " + dataSourceName
|
||||
+ " rule class is invalid. Class List: " + classList);
|
||||
logger.info("[Sentinel Starter] DataSource {} load {} {}", dataSourceName,
|
||||
convertedRuleList.size(), ruleClass.getSimpleName());
|
||||
}
|
||||
}
|
||||
else {
|
||||
logger.error("[Sentinel Starter] DataSource " + dataSourceName
|
||||
+ " rule class is invalid. Class: " + ruleConfig.getClass());
|
||||
throw new RuntimeException("[Sentinel Starter] DataSource " + dataSourceName
|
||||
+ " rule class is invalid. Class: " + ruleConfig.getClass());
|
||||
+ " rule class is not List<" + ruleClass.getSimpleName()
|
||||
+ ">. Class: " + ruleConfig.getClass());
|
||||
throw new IllegalArgumentException("[Sentinel Starter] DataSource "
|
||||
+ dataSourceName + " rule class is not List<"
|
||||
+ ruleClass.getSimpleName() + ">. Class: " + ruleConfig.getClass());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private boolean checkRuleTypeValid(List convertedRuleList) {
|
||||
int matchCount = 0;
|
||||
for (Object rule : convertedRuleList) {
|
||||
if (rulesList.contains(rule.getClass())) {
|
||||
matchCount++;
|
||||
}
|
||||
}
|
||||
return matchCount == convertedRuleList.size();
|
||||
}
|
||||
|
||||
private boolean checkAllRuleTypeSame(List convertedRuleList) {
|
||||
int matchCount = 0;
|
||||
for (Object rule : convertedRuleList) {
|
||||
if (rulesList.contains(rule.getClass())
|
||||
&& rule.getClass() == convertedRuleList.get(0).getClass()) {
|
||||
matchCount++;
|
||||
}
|
||||
}
|
||||
return matchCount == convertedRuleList.size();
|
||||
}
|
||||
|
||||
public List<String> getDataSourceBeanNameList() {
|
||||
return dataSourceBeanNameList;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -17,9 +17,9 @@
|
||||
package org.springframework.cloud.alibaba.sentinel.custom;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.net.URI;
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -29,7 +29,6 @@ import org.springframework.http.HttpRequest;
|
||||
import org.springframework.http.client.ClientHttpRequestExecution;
|
||||
import org.springframework.http.client.ClientHttpRequestInterceptor;
|
||||
import org.springframework.http.client.ClientHttpResponse;
|
||||
import org.springframework.util.ClassUtils;
|
||||
|
||||
import com.alibaba.csp.sentinel.Entry;
|
||||
import com.alibaba.csp.sentinel.SphU;
|
||||
@@ -37,19 +36,18 @@ import com.alibaba.csp.sentinel.Tracer;
|
||||
import com.alibaba.csp.sentinel.context.ContextUtil;
|
||||
import com.alibaba.csp.sentinel.slots.block.BlockException;
|
||||
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
|
||||
import com.alibaba.csp.sentinel.util.StringUtil;
|
||||
|
||||
/**
|
||||
* Interceptor using by SentinelRestTemplate
|
||||
*
|
||||
* @author fangjian
|
||||
* @author <a href="mailto:fangjian0423@gmail.com">Jim</a>
|
||||
*/
|
||||
public class SentinelProtectInterceptor implements ClientHttpRequestInterceptor {
|
||||
|
||||
private static final Logger logger = LoggerFactory
|
||||
.getLogger(SentinelProtectInterceptor.class);
|
||||
|
||||
private SentinelRestTemplate sentinelRestTemplate;
|
||||
private final SentinelRestTemplate sentinelRestTemplate;
|
||||
|
||||
public SentinelProtectInterceptor(SentinelRestTemplate sentinelRestTemplate) {
|
||||
this.sentinelRestTemplate = sentinelRestTemplate;
|
||||
@@ -82,18 +80,7 @@ public class SentinelProtectInterceptor implements ClientHttpRequestInterceptor
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
else {
|
||||
try {
|
||||
return handleBlockException(request, body, execution,
|
||||
(BlockException) e);
|
||||
}
|
||||
catch (Exception ex) {
|
||||
if (ex instanceof IllegalStateException) {
|
||||
throw (IllegalStateException) ex;
|
||||
}
|
||||
throw new IllegalStateException(
|
||||
"sentinel handle BlockException error: " + ex.getMessage(),
|
||||
ex);
|
||||
}
|
||||
return handleBlockException(request, body, execution, (BlockException) e);
|
||||
}
|
||||
}
|
||||
finally {
|
||||
@@ -109,84 +96,49 @@ public class SentinelProtectInterceptor implements ClientHttpRequestInterceptor
|
||||
}
|
||||
|
||||
private ClientHttpResponse handleBlockException(HttpRequest request, byte[] body,
|
||||
ClientHttpRequestExecution execution, BlockException ex) throws Exception {
|
||||
ClientHttpRequestExecution execution, BlockException ex) {
|
||||
Object[] args = new Object[] { request, body, execution, ex };
|
||||
// handle degrade
|
||||
if (isDegradeFailure(ex)) {
|
||||
Method method = extractFallbackMethod(sentinelRestTemplate.fallback(),
|
||||
Method fallbackMethod = extractFallbackMethod(sentinelRestTemplate.fallback(),
|
||||
sentinelRestTemplate.fallbackClass());
|
||||
if (method != null) {
|
||||
return (ClientHttpResponse) method.invoke(null, args);
|
||||
if (fallbackMethod != null) {
|
||||
return methodInvoke(fallbackMethod, args);
|
||||
}
|
||||
else {
|
||||
return new SentinelClientHttpResponse();
|
||||
}
|
||||
}
|
||||
// handle block
|
||||
// handle flow
|
||||
Method blockHandler = extractBlockHandlerMethod(
|
||||
sentinelRestTemplate.blockHandler(),
|
||||
sentinelRestTemplate.blockHandlerClass());
|
||||
if (blockHandler != null) {
|
||||
return (ClientHttpResponse) blockHandler.invoke(null, args);
|
||||
return methodInvoke(blockHandler, args);
|
||||
}
|
||||
else {
|
||||
return new SentinelClientHttpResponse();
|
||||
}
|
||||
}
|
||||
|
||||
private ClientHttpResponse methodInvoke(Method method, Object... args) {
|
||||
try {
|
||||
return (ClientHttpResponse) method.invoke(null, args);
|
||||
}
|
||||
catch (IllegalAccessException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
catch (InvocationTargetException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private Method extractFallbackMethod(String fallback, Class<?> fallbackClass) {
|
||||
if (StringUtil.isBlank(fallback) || fallbackClass == void.class) {
|
||||
return null;
|
||||
}
|
||||
Method cachedMethod = BlockClassRegistry.lookupFallback(fallbackClass, fallback);
|
||||
Class[] args = new Class[] { HttpRequest.class, byte[].class,
|
||||
ClientHttpRequestExecution.class, BlockException.class };
|
||||
if (cachedMethod == null) {
|
||||
cachedMethod = ClassUtils.getStaticMethod(fallbackClass, fallback, args);
|
||||
if (cachedMethod != null) {
|
||||
if (!ClientHttpResponse.class
|
||||
.isAssignableFrom(cachedMethod.getReturnType())) {
|
||||
throw new IllegalStateException(String.format(
|
||||
"the return type of method [%s] in class [%s] is not ClientHttpResponse in degrade",
|
||||
cachedMethod.getName(), fallbackClass.getCanonicalName()));
|
||||
}
|
||||
BlockClassRegistry.updateFallbackFor(fallbackClass, fallback,
|
||||
cachedMethod);
|
||||
}
|
||||
else {
|
||||
throw new IllegalStateException(String.format(
|
||||
"Cannot find method [%s] in class [%s] with parameters %s in degrade",
|
||||
fallback, fallbackClass.getCanonicalName(), Arrays.asList(args)));
|
||||
}
|
||||
}
|
||||
return cachedMethod;
|
||||
return BlockClassRegistry.lookupFallback(fallbackClass, fallback);
|
||||
}
|
||||
|
||||
private Method extractBlockHandlerMethod(String block, Class<?> blockClass) {
|
||||
if (StringUtil.isBlank(block) || blockClass == void.class) {
|
||||
return null;
|
||||
}
|
||||
Method cachedMethod = BlockClassRegistry.lookupBlockHandler(blockClass, block);
|
||||
Class[] args = new Class[] { HttpRequest.class, byte[].class,
|
||||
ClientHttpRequestExecution.class, BlockException.class };
|
||||
if (cachedMethod == null) {
|
||||
cachedMethod = ClassUtils.getStaticMethod(blockClass, block, args);
|
||||
if (cachedMethod != null) {
|
||||
if (!ClientHttpResponse.class
|
||||
.isAssignableFrom(cachedMethod.getReturnType())) {
|
||||
throw new IllegalStateException(String.format(
|
||||
"the return type of method [%s] in class [%s] is not ClientHttpResponse in flow control",
|
||||
cachedMethod.getName(), blockClass.getCanonicalName()));
|
||||
}
|
||||
BlockClassRegistry.updateBlockHandlerFor(blockClass, block, cachedMethod);
|
||||
}
|
||||
else {
|
||||
throw new IllegalStateException(String.format(
|
||||
"Cannot find method [%s] in class [%s] with parameters %s in flow control",
|
||||
block, blockClass.getCanonicalName(), Arrays.asList(args)));
|
||||
}
|
||||
}
|
||||
return cachedMethod;
|
||||
return BlockClassRegistry.lookupBlockHandler(blockClass, block);
|
||||
}
|
||||
|
||||
private boolean isDegradeFailure(BlockException ex) {
|
||||
|
||||
@@ -17,24 +17,20 @@
|
||||
package org.springframework.cloud.alibaba.sentinel.endpoint;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.actuate.endpoint.AbstractEndpoint;
|
||||
import org.springframework.cloud.alibaba.sentinel.SentinelProperties;
|
||||
import org.springframework.cloud.alibaba.sentinel.custom.SentinelDataSourceHandler;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
|
||||
import com.alibaba.csp.sentinel.datasource.ReadableDataSource;
|
||||
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
|
||||
import com.alibaba.csp.sentinel.adapter.servlet.config.WebServletConfig;
|
||||
import com.alibaba.csp.sentinel.config.SentinelConfig;
|
||||
import com.alibaba.csp.sentinel.log.LogBase;
|
||||
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRuleManager;
|
||||
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
|
||||
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
|
||||
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
|
||||
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule;
|
||||
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRuleManager;
|
||||
import com.alibaba.csp.sentinel.slots.system.SystemRule;
|
||||
import com.alibaba.csp.sentinel.slots.system.SystemRuleManager;
|
||||
import com.alibaba.csp.sentinel.transport.config.TransportConfig;
|
||||
|
||||
/**
|
||||
* Endpoint for Sentinel, contains ans properties and rules
|
||||
@@ -42,45 +38,39 @@ import com.alibaba.csp.sentinel.slots.system.SystemRuleManager;
|
||||
*/
|
||||
public class SentinelEndpoint extends AbstractEndpoint<Map<String, Object>> {
|
||||
|
||||
@Autowired
|
||||
private SentinelProperties sentinelProperties;
|
||||
private final SentinelProperties sentinelProperties;
|
||||
|
||||
@Autowired
|
||||
private SentinelDataSourceHandler dataSourceHandler;
|
||||
|
||||
@Autowired
|
||||
private ApplicationContext applicationContext;
|
||||
|
||||
public SentinelEndpoint() {
|
||||
public SentinelEndpoint(SentinelProperties sentinelProperties) {
|
||||
super("sentinel");
|
||||
this.sentinelProperties = sentinelProperties;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Object> invoke() {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
final Map<String, Object> result = new HashMap<>();
|
||||
if (sentinelProperties.isEnabled()) {
|
||||
|
||||
List<FlowRule> flowRules = FlowRuleManager.getRules();
|
||||
List<DegradeRule> degradeRules = DegradeRuleManager.getRules();
|
||||
List<SystemRule> systemRules = SystemRuleManager.getRules();
|
||||
List<ParamFlowRule> paramFlowRules = ParamFlowRuleManager.getRules();
|
||||
result.put("properties", sentinelProperties);
|
||||
result.put("FlowRules", flowRules);
|
||||
result.put("DegradeRules", degradeRules);
|
||||
result.put("SystemRules", systemRules);
|
||||
result.put("ParamFlowRule", paramFlowRules);
|
||||
result.put("datasources", new HashMap<String, Object>());
|
||||
result.put("logDir", LogBase.getLogBaseDir());
|
||||
result.put("logUsePid", LogBase.isLogNameUsePid());
|
||||
result.put("blockPage", WebServletConfig.getBlockPage());
|
||||
result.put("metricsFileSize", SentinelConfig.singleMetricFileSize());
|
||||
result.put("metricsFileCharset", SentinelConfig.charset());
|
||||
result.put("totalMetricsFileCount", SentinelConfig.totalMetricFileCount());
|
||||
result.put("consoleServer", TransportConfig.getConsoleServer());
|
||||
result.put("clientIp", TransportConfig.getHeartbeatClientIp());
|
||||
result.put("heartbeatIntervalMs", TransportConfig.getHeartbeatIntervalMs());
|
||||
result.put("clientPort", TransportConfig.getPort());
|
||||
result.put("coldFactor", sentinelProperties.getFlow().getColdFactor());
|
||||
result.put("filter", sentinelProperties.getFilter());
|
||||
result.put("datasource", sentinelProperties.getDatasource());
|
||||
|
||||
for (String dataSourceBeanName : dataSourceHandler.getDataSourceBeanNameList()) {
|
||||
ReadableDataSource dataSource = applicationContext.getBean(dataSourceBeanName,
|
||||
ReadableDataSource.class);
|
||||
try {
|
||||
((HashMap) result.get("datasources")).put(dataSourceBeanName,
|
||||
dataSource.loadConfig());
|
||||
}
|
||||
catch (Exception e) {
|
||||
((HashMap) result.get("datasources")).put(dataSourceBeanName,
|
||||
"load error: " + e.getMessage());
|
||||
}
|
||||
final Map<String, Object> rules = new HashMap<>();
|
||||
result.put("rules", rules);
|
||||
rules.put("flowRules", FlowRuleManager.getRules());
|
||||
rules.put("degradeRules", DegradeRuleManager.getRules());
|
||||
rules.put("systemRules", SystemRuleManager.getRules());
|
||||
rules.put("authorityRule", AuthorityRuleManager.getRules());
|
||||
rules.put("paramFlowRule", ParamFlowRuleManager.getRules());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -34,8 +34,8 @@ public class SentinelEndpointAutoConfiguration {
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
@ConditionalOnEnabledEndpoint("sentinel")
|
||||
public SentinelEndpoint sentinelEndPoint() {
|
||||
return new SentinelEndpoint();
|
||||
public SentinelEndpoint sentinelEndPoint(SentinelProperties sentinelProperties) {
|
||||
return new SentinelEndpoint(sentinelProperties);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -16,13 +16,6 @@
|
||||
|
||||
package org.springframework.cloud.alibaba.sentinel.rest;
|
||||
|
||||
import org.springframework.cloud.alibaba.sentinel.annotation.SentinelRestTemplate;
|
||||
import org.springframework.cloud.alibaba.sentinel.custom.SentinelProtectInterceptor;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.client.AbstractClientHttpResponse;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
@@ -31,6 +24,13 @@ import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.cloud.alibaba.sentinel.annotation.SentinelRestTemplate;
|
||||
import org.springframework.cloud.alibaba.sentinel.custom.SentinelProtectInterceptor;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.client.AbstractClientHttpResponse;
|
||||
|
||||
/**
|
||||
* Using by {@link SentinelRestTemplate} and {@link SentinelProtectInterceptor}
|
||||
*
|
||||
@@ -41,7 +41,6 @@ public class SentinelClientHttpResponse extends AbstractClientHttpResponse {
|
||||
private String blockResponse = "RestTemplate request block by sentinel";
|
||||
|
||||
public SentinelClientHttpResponse() {
|
||||
|
||||
}
|
||||
|
||||
public SentinelClientHttpResponse(String blockResponse) {
|
||||
|
||||
@@ -18,6 +18,11 @@
|
||||
"defaultValue": "8719",
|
||||
"description": "sentinel api port."
|
||||
},
|
||||
{
|
||||
"name": "spring.cloud.sentinel.transport.clientIp",
|
||||
"type": "java.lang.String",
|
||||
"description": "sentinel client ip connect to dashboard."
|
||||
},
|
||||
{
|
||||
"name": "spring.cloud.sentinel.transport.dashboard",
|
||||
"type": "java.lang.String",
|
||||
|
||||
@@ -3,3 +3,6 @@ org.springframework.cloud.alibaba.sentinel.SentinelWebAutoConfiguration,\
|
||||
org.springframework.cloud.alibaba.sentinel.endpoint.SentinelEndpointAutoConfiguration,\
|
||||
org.springframework.cloud.alibaba.sentinel.custom.SentinelAutoConfiguration,\
|
||||
org.springframework.cloud.alibaba.sentinel.feign.SentinelFeignAutoConfiguration
|
||||
|
||||
org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker=\
|
||||
org.springframework.cloud.alibaba.sentinel.custom.SentinelCircuitBreakerConfiguration
|
||||
@@ -27,8 +27,12 @@ import org.springframework.cloud.alibaba.sentinel.annotation.SentinelRestTemplat
|
||||
import org.springframework.cloud.alibaba.sentinel.custom.SentinelAutoConfiguration;
|
||||
import org.springframework.cloud.alibaba.sentinel.custom.SentinelBeanPostProcessor;
|
||||
import org.springframework.cloud.alibaba.sentinel.custom.SentinelProtectInterceptor;
|
||||
import org.springframework.cloud.alibaba.sentinel.rest.SentinelClientHttpResponse;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.HttpRequest;
|
||||
import org.springframework.http.client.ClientHttpRequestExecution;
|
||||
import org.springframework.http.client.ClientHttpResponse;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
|
||||
|
||||
@@ -109,8 +113,9 @@ public class SentinelAutoConfigurationTests {
|
||||
}
|
||||
|
||||
static class ExceptionUtil {
|
||||
public static void handleException(BlockException ex) {
|
||||
System.out.println("Oops: " + ex.getClass().getCanonicalName());
|
||||
public static ClientHttpResponse handleException(HttpRequest request, byte[] body,
|
||||
ClientHttpRequestExecution execution, BlockException ex) {
|
||||
return new SentinelClientHttpResponse("custom block info");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user