1
0
mirror of https://gitee.com/mirrors/Spring-Cloud-Alibaba.git synced 2021-06-26 13:25:11 +08:00

Polish alibaba/spring-cloud-alibaba#1758 : [CodeBase] Sync the source code from greenwich to finichley

This commit is contained in:
mercyblitz 2020-09-21 14:15:52 +08:00
parent 4252051ec6
commit 8614a9c3be
18 changed files with 265 additions and 284 deletions

View File

@ -102,6 +102,20 @@ public class SentinelProperties {
*/
private Boolean httpMethodSpecify = false;
/**
* Specify whether unify web context(i.e. use the default context name), and is true
* by default.
*/
private Boolean webContextUnify = true;
public Boolean getWebContextUnify() {
return webContextUnify;
}
public void setWebContextUnify(Boolean webContextUnify) {
this.webContextUnify = webContextUnify;
}
public boolean isEager() {
return eager;
}
@ -218,9 +232,8 @@ public class SentinelProperties {
private String blockPage;
@Deprecated
@DeprecatedConfigurationProperty(
reason = "replaced to SentinelProperties#blockPage.",
replacement = SentinelConstants.PROPERTY_PREFIX + ".block-page")
@DeprecatedConfigurationProperty(reason = "replaced to SentinelProperties#blockPage.", replacement = SentinelConstants.PROPERTY_PREFIX
+ ".block-page")
public String getBlockPage() {
return blockPage;
}

View File

@ -83,19 +83,18 @@ public class SentinelWebAutoConfiguration implements WebMvcConfigurer {
}
@Bean
@ConditionalOnProperty(name = "spring.cloud.sentinel.filter.enabled",
matchIfMissing = true)
@ConditionalOnProperty(name = "spring.cloud.sentinel.filter.enabled", matchIfMissing = true)
public SentinelWebInterceptor sentinelWebInterceptor(
SentinelWebMvcConfig sentinelWebMvcConfig) {
return new SentinelWebInterceptor(sentinelWebMvcConfig);
}
@Bean
@ConditionalOnProperty(name = "spring.cloud.sentinel.filter.enabled",
matchIfMissing = true)
@ConditionalOnProperty(name = "spring.cloud.sentinel.filter.enabled", matchIfMissing = true)
public SentinelWebMvcConfig sentinelWebMvcConfig() {
SentinelWebMvcConfig sentinelWebMvcConfig = new SentinelWebMvcConfig();
sentinelWebMvcConfig.setHttpMethodSpecify(properties.getHttpMethodSpecify());
sentinelWebMvcConfig.setWebContextUnify(properties.getWebContextUnify());
if (blockExceptionHandlerOptional.isPresent()) {
blockExceptionHandlerOptional

View File

@ -77,16 +77,14 @@ public class SentinelWebFluxAutoConfiguration {
@Bean
@Order(-2)
@ConditionalOnProperty(name = "spring.cloud.sentinel.filter.enabled",
matchIfMissing = true)
@ConditionalOnProperty(name = "spring.cloud.sentinel.filter.enabled", matchIfMissing = true)
public SentinelBlockExceptionHandler sentinelBlockExceptionHandler() {
return new SentinelBlockExceptionHandler(viewResolvers, serverCodecConfigurer);
}
@Bean
@Order(-1)
@ConditionalOnProperty(name = "spring.cloud.sentinel.filter.enabled",
matchIfMissing = true)
@ConditionalOnProperty(name = "spring.cloud.sentinel.filter.enabled", matchIfMissing = true)
public SentinelWebFluxFilter sentinelWebFluxFilter() {
log.info("[Sentinel Starter] register Sentinel SentinelWebFluxFilter");
return new SentinelWebFluxFilter();

View File

@ -31,7 +31,6 @@ 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;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
@ -79,9 +78,9 @@ public class SentinelAutoConfiguration {
System.setProperty(LogBase.LOG_NAME_USE_PID,
String.valueOf(properties.getLog().isSwitchPid()));
}
if (StringUtils.isEmpty(System.getProperty(AppNameUtil.APP_NAME))
if (StringUtils.isEmpty(System.getProperty(SentinelConfig.APP_NAME_PROP_KEY))
&& StringUtils.hasText(projectName)) {
System.setProperty(AppNameUtil.APP_NAME, projectName);
System.setProperty(SentinelConfig.APP_NAME_PROP_KEY, projectName);
}
if (StringUtils.isEmpty(System.getProperty(TransportConfig.SERVER_PORT))
&& StringUtils.hasText(properties.getTransport().getPort())) {
@ -146,8 +145,7 @@ public class SentinelAutoConfiguration {
@Bean
@ConditionalOnMissingBean
@ConditionalOnClass(name = "org.springframework.web.client.RestTemplate")
@ConditionalOnProperty(name = "resttemplate.sentinel.enabled", havingValue = "true",
matchIfMissing = true)
@ConditionalOnProperty(name = "resttemplate.sentinel.enabled", havingValue = "true", matchIfMissing = true)
public SentinelBeanPostProcessor sentinelBeanPostProcessor(
ApplicationContext applicationContext) {
return new SentinelBeanPostProcessor(applicationContext);
@ -156,8 +154,8 @@ public class SentinelAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public SentinelDataSourceHandler sentinelDataSourceHandler(
DefaultListableBeanFactory beanFactory, SentinelProperties sentinelProperties,
Environment env) {
DefaultListableBeanFactory beanFactory, SentinelProperties sentinelProperties,
Environment env) {
return new SentinelDataSourceHandler(beanFactory, sentinelProperties, env);
}

View File

@ -65,7 +65,7 @@ public class SentinelBeanPostProcessor implements MergedBeanDefinitionPostProces
@Override
public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition,
Class<?> beanType, String beanName) {
Class<?> beanType, String beanName) {
if (checkSentinelProtect(beanDefinition, beanType, beanName)) {
SentinelRestTemplate sentinelRestTemplate;
if (beanDefinition.getSource() instanceof StandardMethodMetadata) {
@ -166,7 +166,7 @@ public class SentinelBeanPostProcessor implements MergedBeanDefinitionPostProces
}
private boolean checkSentinelProtect(RootBeanDefinition beanDefinition,
Class<?> beanType, String beanName) {
Class<?> beanType, String beanName) {
return beanName != null && beanType == RestTemplate.class
&& checkMethodMetadataReadingVisitor(beanDefinition);
}

View File

@ -68,7 +68,7 @@ public class SentinelDataSourceHandler implements SmartInitializingSingleton {
private final Environment env;
public SentinelDataSourceHandler(DefaultListableBeanFactory beanFactory,
SentinelProperties sentinelProperties, Environment env) {
SentinelProperties sentinelProperties, Environment env) {
this.beanFactory = beanFactory;
this.sentinelProperties = sentinelProperties;
this.env = env;

View File

@ -55,7 +55,7 @@ public class SentinelProtectInterceptor implements ClientHttpRequestInterceptor
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
ClientHttpRequestExecution execution) throws IOException {
ClientHttpRequestExecution execution) throws IOException {
URI uri = request.getURI();
String hostResource = request.getMethod().toString() + ":" + uri.getScheme()
+ "://" + uri.getHost()
@ -107,7 +107,7 @@ public class SentinelProtectInterceptor implements ClientHttpRequestInterceptor
}
private ClientHttpResponse handleBlockException(HttpRequest request, byte[] body,
ClientHttpRequestExecution execution, BlockException ex) {
ClientHttpRequestExecution execution, BlockException ex) {
Object[] args = new Object[] { request, body, execution, ex };
// handle degrade
if (isDegradeFailure(ex)) {

View File

@ -61,7 +61,7 @@ public class SentinelEndpoint {
result.put("metricsFileSize", SentinelConfig.singleMetricFileSize());
result.put("metricsFileCharset", SentinelConfig.charset());
result.put("totalMetricsFileCount", SentinelConfig.totalMetricFileCount());
result.put("consoleServer", TransportConfig.getConsoleServer());
result.put("consoleServer", TransportConfig.getConsoleServerList());
result.put("clientIp", TransportConfig.getHeartbeatClientIp());
result.put("heartbeatIntervalMs", TransportConfig.getHeartbeatIntervalMs());
result.put("clientPort", TransportConfig.getPort());

View File

@ -17,6 +17,7 @@
package com.alibaba.cloud.sentinel.endpoint;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alibaba.cloud.sentinel.SentinelProperties;
@ -24,13 +25,14 @@ import com.alibaba.csp.sentinel.datasource.AbstractDataSource;
import com.alibaba.csp.sentinel.heartbeat.HeartbeatSenderProvider;
import com.alibaba.csp.sentinel.transport.HeartbeatSender;
import com.alibaba.csp.sentinel.transport.config.TransportConfig;
import com.alibaba.csp.sentinel.util.function.Tuple2;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.boot.actuate.health.AbstractHealthIndicator;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.boot.actuate.health.Status;
import org.springframework.util.StringUtils;
import org.springframework.util.CollectionUtils;
/**
* A {@link HealthIndicator} for Sentinel, which checks the status of Sentinel Dashboard
@ -61,7 +63,7 @@ public class SentinelHealthIndicator extends AbstractHealthIndicator {
private SentinelProperties sentinelProperties;
public SentinelHealthIndicator(DefaultListableBeanFactory beanFactory,
SentinelProperties sentinelProperties) {
SentinelProperties sentinelProperties) {
this.beanFactory = beanFactory;
this.sentinelProperties = sentinelProperties;
}
@ -74,7 +76,7 @@ public class SentinelHealthIndicator extends AbstractHealthIndicator {
// detail
if (!sentinelProperties.isEnabled()) {
detailMap.put("enabled", false);
withDetails(builder.up(), detailMap);
builder.up().withDetails(detailMap);
return;
}
@ -82,8 +84,9 @@ public class SentinelHealthIndicator extends AbstractHealthIndicator {
// Check health of Dashboard
boolean dashboardUp = true;
String consoleServer = TransportConfig.getConsoleServer();
if (StringUtils.isEmpty(consoleServer)) {
List<Tuple2<String, Integer>> consoleServerList = TransportConfig
.getConsoleServerList();
if (CollectionUtils.isEmpty(consoleServerList)) {
// If Dashboard isn't configured, it's OK and mark the status of Dashboard
// with UNKNOWN.
detailMap.put("dashboard",
@ -101,8 +104,10 @@ public class SentinelHealthIndicator extends AbstractHealthIndicator {
else {
// If failed to send heartbeat message, means that the Dashboard is DOWN
dashboardUp = false;
detailMap.put("dashboard", new Status(Status.DOWN.getCode(),
consoleServer + " can't be connected"));
detailMap.put("dashboard",
new Status(Status.UNKNOWN.getCode(), String.format(
"the dashboard servers [%s] one of them can't be connected",
consoleServerList)));
}
}
@ -133,22 +138,17 @@ public class SentinelHealthIndicator extends AbstractHealthIndicator {
// DOWN
dataSourceUp = false;
dataSourceDetailMap.put(dataSourceBeanName,
new Status(Status.DOWN.getCode(), e.getMessage()));
new Status(Status.UNKNOWN.getCode(), e.getMessage()));
}
}
// If Dashboard and DataSource are both OK, the health status is UP
if (dashboardUp && dataSourceUp) {
withDetails(builder.up(), detailMap);
builder.up().withDetails(detailMap);
}
else {
withDetails(builder.down(), detailMap);
builder.unknown().withDetails(detailMap);
}
}
private void withDetails(Health.Builder builder, Map<String, Object> detailMap) {
for (String key : detailMap.keySet()) {
builder.withDetail(key, detailMap.get(key));
}
}
}

View File

@ -33,6 +33,7 @@ import org.springframework.cloud.openfeign.FeignContext;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;
/**
* {@link Feign.Builder} like {@link HystrixFeign.Builder}.
@ -75,7 +76,7 @@ public final class SentinelFeign {
super.invocationHandlerFactory(new InvocationHandlerFactory() {
@Override
public InvocationHandler create(Target target,
Map<Method, MethodHandler> dispatch) {
Map<Method, MethodHandler> dispatch) {
// using reflect get fallback and fallbackFactory properties from
// FeignClientFactoryBean because FeignClientFactoryBean is a package
// level class, we can not use it in our package
@ -86,7 +87,11 @@ public final class SentinelFeign {
"fallback");
Class fallbackFactory = (Class) getFieldValue(feignClientFactoryBean,
"fallbackFactory");
String beanName = (String) getFieldValue(feignClientFactoryBean, "name");
String beanName = (String) getFieldValue(feignClientFactoryBean,
"contextId");
if (!StringUtils.hasText(beanName)) {
beanName = (String) getFieldValue(feignClientFactoryBean, "name");
}
Object fallbackInstance;
FallbackFactory fallbackFactoryInstance;

View File

@ -53,7 +53,7 @@ public class SentinelInvocationHandler implements InvocationHandler {
private Map<Method, Method> fallbackMethodMap;
SentinelInvocationHandler(Target<?> target, Map<Method, MethodHandler> dispatch,
FallbackFactory fallbackFactory) {
FallbackFactory fallbackFactory) {
this.target = checkNotNull(target, "target");
this.dispatch = checkNotNull(dispatch, "dispatch");
this.fallbackFactory = fallbackFactory;
@ -99,7 +99,7 @@ public class SentinelInvocationHandler implements InvocationHandler {
}
else {
String resourceName = methodMetadata.template().method().toUpperCase()
+ ":" + hardCodedTarget.url() + methodMetadata.template().url();
+ ":" + hardCodedTarget.url() + methodMetadata.template().path();
Entry entry = null;
try {
ContextUtil.enter(resourceName);

View File

@ -19,7 +19,12 @@
"description": "earlier initialize heart-beat when the spring container starts when the transport dependency is on classpath, the configuration is effective."
},
{
"name": "spring.cloud.sentinel.transport.port",
"name": "spring.cloud.sentinel.web-context-unify",
"type": "java.lang.Boolean",
"defaultValue": true,
"description": "Specify whether unify web context(i.e. use the default context name), and is true by default."
},
{ "name": "spring.cloud.sentinel.transport.port",
"type": "java.lang.String",
"defaultValue": "8719",
"description": "sentinel api port."

View File

@ -1,136 +1,132 @@
///*
// * Copyright 2013-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 com.alibaba.cloud.sentinel;
//
//import com.alibaba.cloud.sentinel.feign.SentinelFeignAutoConfiguration;
//import org.junit.Test;
//import org.junit.runner.RunWith;
//
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
//import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
//import org.springframework.boot.test.context.SpringBootTest;
//import org.springframework.cloud.openfeign.EnableFeignClients;
//import org.springframework.cloud.openfeign.FeignClient;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.test.context.junit4.SpringRunner;
//import org.springframework.web.bind.annotation.GetMapping;
//import org.springframework.web.bind.annotation.PathVariable;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RequestParam;
//
//import static org.assertj.core.api.Assertions.assertThat;
//
///**
// * Add this unit test to verify https://github.com/alibaba/spring-cloud-alibaba/pull/838.
// *
// * @author <a href="mailto:fangjian0423@gmail.com">Jim</a>
// */
//@RunWith(SpringRunner.class)
//@SpringBootTest(classes = { ContextIdSentinelFeignTests.TestConfig.class },
// properties = { "feign.sentinel.enabled=true" })
//public class ContextIdSentinelFeignTests {
//
// @Autowired
// private EchoService echoService;
//
// @Autowired
// private FooService fooService;
//
// @Test
// public void testFeignClient() {
// assertThat(echoService.echo("test")).isEqualTo("echo fallback");
// assertThat(fooService.echo("test")).isEqualTo("foo fallback");
// assertThat(fooService.toString()).isNotEqualTo(echoService.toString());
// assertThat(fooService.hashCode()).isNotEqualTo(echoService.hashCode());
// assertThat(echoService.equals(fooService)).isEqualTo(Boolean.FALSE);
// }
//
// @Configuration
// @EnableAutoConfiguration
// @ImportAutoConfiguration({ SentinelFeignAutoConfiguration.class })
// @EnableFeignClients
// public static class TestConfig {
//
// }
//
// @FeignClient(name = "service-provider",
// fallback = EchoServiceFallback.class,
// configuration = FeignConfiguration.class)
// public interface EchoService {
//
// @GetMapping("/echo/{str}")
// String echo(@PathVariable("str") String str);
//
// }
//
// @FeignClient(value = "foo-service",
// fallbackFactory = CustomFallbackFactory.class,
// configuration = FeignConfiguration.class)
// public interface FooService {
//
// @RequestMapping(path = "echo/{str}")
// String echo(@RequestParam("str") String param);
//
// }
//
// public static class FeignConfiguration {
//
// @Bean
// public EchoServiceFallback echoServiceFallback() {
// return new EchoServiceFallback();
// }
//
// @Bean
// public CustomFallbackFactory customFallbackFactory() {
// return new CustomFallbackFactory();
// }
//
// }
//
// public static class EchoServiceFallback implements EchoService {
//
// @Override
// public String echo(@RequestParam("str") String param) {
// return "echo fallback";
// }
//
// }
//
// public static class FooServiceFallback implements FooService {
//
// @Override
// public String echo(@RequestParam("str") String param) {
// return "foo fallback";
// }
//
// }
//
// public static class CustomFallbackFactory
// implements feign.hystrix.FallbackFactory<FooService> {
//
// private FooService fooService = new FooServiceFallback();
//
// @Override
// public FooService create(Throwable throwable) {
// return fooService;
// }
//
// }
//
//}
/*
* Copyright 2013-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 com.alibaba.cloud.sentinel;
import com.alibaba.cloud.sentinel.feign.SentinelFeignAutoConfiguration;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Add this unit test to verify https://github.com/alibaba/spring-cloud-alibaba/pull/838.
*
* @author <a href="mailto:fangjian0423@gmail.com">Jim</a>
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = { ContextIdSentinelFeignTests.TestConfig.class }, properties = {
"feign.sentinel.enabled=true" })
public class ContextIdSentinelFeignTests {
@Autowired
private EchoService echoService;
@Autowired
private FooService fooService;
@Test
public void testFeignClient() {
assertThat(echoService.echo("test")).isEqualTo("echo fallback");
assertThat(fooService.echo("test")).isEqualTo("foo fallback");
assertThat(fooService.toString()).isNotEqualTo(echoService.toString());
assertThat(fooService.hashCode()).isNotEqualTo(echoService.hashCode());
assertThat(echoService.equals(fooService)).isEqualTo(Boolean.FALSE);
}
@Configuration
@EnableAutoConfiguration
@ImportAutoConfiguration({ SentinelFeignAutoConfiguration.class })
@EnableFeignClients
public static class TestConfig {
}
@FeignClient(contextId = "echoService", name = "service-provider", fallback = EchoServiceFallback.class, configuration = FeignConfiguration.class)
public interface EchoService {
@GetMapping("/echo/{str}")
String echo(@PathVariable("str") String str);
}
@FeignClient(contextId = "fooService", value = "foo-service", fallbackFactory = CustomFallbackFactory.class, configuration = FeignConfiguration.class)
public interface FooService {
@RequestMapping(path = "echo/{str}")
String echo(@RequestParam("str") String param);
}
public static class FeignConfiguration {
@Bean
public EchoServiceFallback echoServiceFallback() {
return new EchoServiceFallback();
}
@Bean
public CustomFallbackFactory customFallbackFactory() {
return new CustomFallbackFactory();
}
}
public static class EchoServiceFallback implements EchoService {
@Override
public String echo(@RequestParam("str") String param) {
return "echo fallback";
}
}
public static class FooServiceFallback implements FooService {
@Override
public String echo(@RequestParam("str") String param) {
return "foo fallback";
}
}
public static class CustomFallbackFactory
implements feign.hystrix.FallbackFactory<FooService> {
private FooService fooService = new FooServiceFallback();
@Override
public FooService create(Throwable throwable) {
return fooService;
}
}
}

View File

@ -28,11 +28,10 @@ import com.alibaba.csp.sentinel.config.SentinelConfig;
import com.alibaba.csp.sentinel.log.LogBase;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
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.transport.config.TransportConfig;
import com.alibaba.csp.sentinel.util.function.Tuple2;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@ -64,8 +63,9 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
* @author jiashuai.xie
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = { SentinelAutoConfigurationTests.TestConfig.class },
properties = { "spring.cloud.sentinel.filter.order=123",
@SpringBootTest(classes = {
SentinelAutoConfigurationTests.TestConfig.class }, properties = {
"spring.cloud.sentinel.filter.order=123",
"spring.cloud.sentinel.filter.urlPatterns=/*,/test",
"spring.cloud.sentinel.metric.fileSingleSize=9999",
"spring.cloud.sentinel.metric.fileTotalCount=100",
@ -73,11 +73,10 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
"spring.cloud.sentinel.flow.coldFactor=3",
"spring.cloud.sentinel.eager=true",
"spring.cloud.sentinel.log.switchPid=true",
"spring.cloud.sentinel.transport.dashboard=http://localhost:8080",
"spring.cloud.sentinel.transport.dashboard=http://localhost:8080,http://localhost:8081",
"spring.cloud.sentinel.transport.port=9999",
"spring.cloud.sentinel.transport.clientIp=1.1.1.1",
"spring.cloud.sentinel.transport.heartbeatIntervalMs=20000" },
webEnvironment = RANDOM_PORT)
"spring.cloud.sentinel.transport.heartbeatIntervalMs=20000" }, webEnvironment = RANDOM_PORT)
public class SentinelAutoConfigurationTests {
@Autowired
@ -115,13 +114,6 @@ public class SentinelAutoConfigurationTests {
rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);
rule.setStrategy(RuleConstant.STRATEGY_DIRECT);
FlowRuleManager.loadRules(Arrays.asList(rule));
DegradeRule degradeRule = new DegradeRule();
degradeRule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT);
degradeRule.setResource("GET:" + degradeUrl);
degradeRule.setCount(0);
degradeRule.setTimeWindow(60);
DegradeRuleManager.loadRules(Arrays.asList(degradeRule));
}
@Test
@ -142,7 +134,9 @@ public class SentinelAutoConfigurationTests {
Map<String, Object> map = sentinelEndpoint.invoke();
assertThat(map.get("logUsePid")).isEqualTo(Boolean.TRUE);
assertThat(map.get("consoleServer")).isEqualTo("http://localhost:8080");
assertThat(map.get("consoleServer").toString()).isEqualTo(
Arrays.asList(Tuple2.of("localhost", 8080), Tuple2.of("localhost", 8081))
.toString());
assertThat(map.get("clientPort")).isEqualTo("9999");
assertThat(map.get("heartbeatIntervalMs")).isEqualTo(20000L);
assertThat(map.get("clientIp")).isEqualTo("1.1.1.1");
@ -174,7 +168,7 @@ public class SentinelAutoConfigurationTests {
private void checkSentinelTransport() {
assertThat(sentinelProperties.getTransport().getPort()).isEqualTo("9999");
assertThat(sentinelProperties.getTransport().getDashboard())
.isEqualTo("http://localhost:8080");
.isEqualTo("http://localhost:8080,http://localhost:8081");
assertThat(sentinelProperties.getTransport().getClientIp()).isEqualTo("1.1.1.1");
assertThat(sentinelProperties.getTransport().getHeartbeatIntervalMs())
.isEqualTo("20000");
@ -191,7 +185,9 @@ public class SentinelAutoConfigurationTests {
@Test
public void testSentinelSystemProperties() {
assertThat(LogBase.isLogNameUsePid()).isEqualTo(true);
assertThat(TransportConfig.getConsoleServer()).isEqualTo("http://localhost:8080");
assertThat(TransportConfig.getConsoleServerList().toString()).isEqualTo(
Arrays.asList(Tuple2.of("localhost", 8080), Tuple2.of("localhost", 8081))
.toString());
assertThat(TransportConfig.getPort()).isEqualTo("9999");
assertThat(TransportConfig.getHeartbeatIntervalMs().longValue())
.isEqualTo(20000L);
@ -203,7 +199,7 @@ public class SentinelAutoConfigurationTests {
}
@Test
public void testFlowRestTemplate() {
public void testRestTemplateBlockHandler() {
assertThat(restTemplate.getInterceptors().size()).isEqualTo(2);
assertThat(restTemplateWithBlockClass.getInterceptors().size()).isEqualTo(1);
@ -231,42 +227,31 @@ public class SentinelAutoConfigurationTests {
}).isInstanceOf(RestClientException.class);
}
@Test
public void testFallbackRestTemplate() {
ResponseEntity responseEntity = restTemplateWithFallbackClass
.getForEntity(degradeUrl, String.class);
assertThat(responseEntity.getBody()).isEqualTo("Oops fallback");
assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.OK);
}
@Configuration
static class SentinelTestConfiguration {
@Bean
@SentinelRestTemplate
RestTemplate restTemplate() {
RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
restTemplate.getInterceptors().add(mock(ClientHttpRequestInterceptor.class));
return restTemplate;
}
@Bean
@SentinelRestTemplate(blockHandlerClass = ExceptionUtil.class,
blockHandler = "handleException")
RestTemplate restTemplateWithBlockClass() {
@SentinelRestTemplate(blockHandlerClass = ExceptionUtil.class, blockHandler = "handleException")
RestTemplate restTemplateWithBlockClass() {
return new RestTemplate();
}
@Bean
@SentinelRestTemplate(fallbackClass = ExceptionUtil.class,
fallback = "fallbackException")
RestTemplate restTemplateWithFallbackClass() {
@SentinelRestTemplate(fallbackClass = ExceptionUtil.class, fallback = "fallbackException")
RestTemplate restTemplateWithFallbackClass() {
return new RestTemplate();
}
@Bean
RestTemplate restTemplateWithoutBlockClass() {
RestTemplate restTemplateWithoutBlockClass() {
return new RestTemplate();
}
@ -275,13 +260,13 @@ public class SentinelAutoConfigurationTests {
public static class ExceptionUtil {
public static SentinelClientHttpResponse handleException(HttpRequest request,
byte[] body, ClientHttpRequestExecution execution, BlockException ex) {
byte[] body, ClientHttpRequestExecution execution, BlockException ex) {
System.out.println("Oops: " + ex.getClass().getCanonicalName());
return new SentinelClientHttpResponse("Oops");
}
public static SentinelClientHttpResponse fallbackException(HttpRequest request,
byte[] body, ClientHttpRequestExecution execution, BlockException ex) {
byte[] body, ClientHttpRequestExecution execution, BlockException ex) {
System.out.println("Oops: " + ex.getClass().getCanonicalName());
return new SentinelClientHttpResponse("Oops fallback");
}

View File

@ -41,8 +41,8 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author <a href="mailto:fangjian0423@gmail.com">Jim</a>
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = { SentinelBeanAutowiredTests.TestConfig.class },
properties = { "spring.cloud.sentinel.filter.order=111" })
@SpringBootTest(classes = { SentinelBeanAutowiredTests.TestConfig.class }, properties = {
"spring.cloud.sentinel.filter.order=111" })
public class SentinelBeanAutowiredTests {
@Autowired

View File

@ -45,8 +45,8 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy;
* @author <a href="mailto:fangjian0423@gmail.com">Jim</a>
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = { SentinelFeignTests.TestConfig.class },
properties = { "feign.sentinel.enabled=true" })
@SpringBootTest(classes = { SentinelFeignTests.TestConfig.class }, properties = {
"feign.sentinel.enabled=true" })
public class SentinelFeignTests {
@Autowired

View File

@ -114,14 +114,14 @@ public class SentinelRestTemplateTests {
public static class TestConfig1 {
@Bean
SentinelBeanPostProcessor sentinelBeanPostProcessor(
SentinelBeanPostProcessor sentinelBeanPostProcessor(
ApplicationContext applicationContext) {
return new SentinelBeanPostProcessor(applicationContext);
}
@Bean
@SentinelRestTemplate(fallback = "fbk")
RestTemplate restTemplate() {
RestTemplate restTemplate() {
return new RestTemplate();
}
@ -131,14 +131,14 @@ public class SentinelRestTemplateTests {
public static class TestConfig2 {
@Bean
SentinelBeanPostProcessor sentinelBeanPostProcessor(
SentinelBeanPostProcessor sentinelBeanPostProcessor(
ApplicationContext applicationContext) {
return new SentinelBeanPostProcessor(applicationContext);
}
@Bean
@SentinelRestTemplate(fallbackClass = ExceptionUtil.class)
RestTemplate restTemplate() {
RestTemplate restTemplate() {
return new RestTemplate();
}
@ -148,14 +148,14 @@ public class SentinelRestTemplateTests {
public static class TestConfig3 {
@Bean
SentinelBeanPostProcessor sentinelBeanPostProcessor(
SentinelBeanPostProcessor sentinelBeanPostProcessor(
ApplicationContext applicationContext) {
return new SentinelBeanPostProcessor(applicationContext);
}
@Bean
@SentinelRestTemplate(blockHandler = "blk")
RestTemplate restTemplate() {
RestTemplate restTemplate() {
return new RestTemplate();
}
@ -165,14 +165,14 @@ public class SentinelRestTemplateTests {
public static class TestConfig4 {
@Bean
SentinelBeanPostProcessor sentinelBeanPostProcessor(
SentinelBeanPostProcessor sentinelBeanPostProcessor(
ApplicationContext applicationContext) {
return new SentinelBeanPostProcessor(applicationContext);
}
@Bean
@SentinelRestTemplate(blockHandlerClass = ExceptionUtil.class)
RestTemplate restTemplate() {
RestTemplate restTemplate() {
return new RestTemplate();
}
@ -182,20 +182,14 @@ public class SentinelRestTemplateTests {
public static class TestConfig5 {
@Bean
SentinelBeanPostProcessor sentinelBeanPostProcessor(
SentinelBeanPostProcessor sentinelBeanPostProcessor(
ApplicationContext applicationContext) {
return new SentinelBeanPostProcessor(applicationContext);
}
@Bean
@SentinelRestTemplate(
blockHandlerClass = SentinelRestTemplateTests.ExceptionUtil.class,
blockHandler = "handleException",
fallbackClass = SentinelRestTemplateTests.ExceptionUtil.class,
fallback = "fallbackException",
urlCleanerClass = SentinelRestTemplateTests.UrlCleanUtil.class,
urlCleaner = "clean")
RestTemplate restTemplate() {
@SentinelRestTemplate(blockHandlerClass = ExceptionUtil.class, blockHandler = "handleException", fallbackClass = ExceptionUtil.class, fallback = "fallbackException", urlCleanerClass = UrlCleanUtil.class, urlCleaner = "clean")
RestTemplate restTemplate() {
return new RestTemplate();
}
@ -205,16 +199,14 @@ public class SentinelRestTemplateTests {
public static class TestConfig6 {
@Bean
SentinelBeanPostProcessor sentinelBeanPostProcessor(
SentinelBeanPostProcessor sentinelBeanPostProcessor(
ApplicationContext applicationContext) {
return new SentinelBeanPostProcessor(applicationContext);
}
@Bean
@SentinelRestTemplate(
blockHandlerClass = SentinelRestTemplateTests.ExceptionUtil.class,
blockHandler = "handleException1")
RestTemplate restTemplate() {
@SentinelRestTemplate(blockHandlerClass = ExceptionUtil.class, blockHandler = "handleException1")
RestTemplate restTemplate() {
return new RestTemplate();
}
@ -224,16 +216,14 @@ public class SentinelRestTemplateTests {
public static class TestConfig7 {
@Bean
SentinelBeanPostProcessor sentinelBeanPostProcessor(
SentinelBeanPostProcessor sentinelBeanPostProcessor(
ApplicationContext applicationContext) {
return new SentinelBeanPostProcessor(applicationContext);
}
@Bean
@SentinelRestTemplate(
fallbackClass = SentinelRestTemplateTests.ExceptionUtil.class,
fallback = "fallbackException1")
RestTemplate restTemplate() {
@SentinelRestTemplate(fallbackClass = ExceptionUtil.class, fallback = "fallbackException1")
RestTemplate restTemplate() {
return new RestTemplate();
}
@ -243,16 +233,14 @@ public class SentinelRestTemplateTests {
public static class TestConfig8 {
@Bean
SentinelBeanPostProcessor sentinelBeanPostProcessor(
SentinelBeanPostProcessor sentinelBeanPostProcessor(
ApplicationContext applicationContext) {
return new SentinelBeanPostProcessor(applicationContext);
}
@Bean
@SentinelRestTemplate(
blockHandlerClass = SentinelRestTemplateTests.ExceptionUtil.class,
blockHandler = "handleException2")
RestTemplate restTemplate() {
@SentinelRestTemplate(blockHandlerClass = ExceptionUtil.class, blockHandler = "handleException2")
RestTemplate restTemplate() {
return new RestTemplate();
}
@ -262,16 +250,14 @@ public class SentinelRestTemplateTests {
public static class TestConfig9 {
@Bean
SentinelBeanPostProcessor sentinelBeanPostProcessor(
SentinelBeanPostProcessor sentinelBeanPostProcessor(
ApplicationContext applicationContext) {
return new SentinelBeanPostProcessor(applicationContext);
}
@Bean
@SentinelRestTemplate(
fallbackClass = SentinelRestTemplateTests.ExceptionUtil.class,
fallback = "fallbackException2")
RestTemplate restTemplate() {
@SentinelRestTemplate(fallbackClass = ExceptionUtil.class, fallback = "fallbackException2")
RestTemplate restTemplate() {
return new RestTemplate();
}
@ -281,20 +267,20 @@ public class SentinelRestTemplateTests {
public static class TestConfig10 {
@Bean
SentinelBeanPostProcessor sentinelBeanPostProcessor(
SentinelBeanPostProcessor sentinelBeanPostProcessor(
ApplicationContext applicationContext) {
return new SentinelBeanPostProcessor(applicationContext);
}
@Bean
@SentinelRestTemplate
RestTemplate restTemplate() {
RestTemplate restTemplate() {
return new RestTemplate();
}
@Bean
@SentinelRestTemplate
RestTemplate restTemplate2() {
RestTemplate restTemplate2() {
return new RestTemplate();
}
@ -304,14 +290,14 @@ public class SentinelRestTemplateTests {
public static class TestConfig11 {
@Bean
SentinelBeanPostProcessor sentinelBeanPostProcessor(
SentinelBeanPostProcessor sentinelBeanPostProcessor(
ApplicationContext applicationContext) {
return new SentinelBeanPostProcessor(applicationContext);
}
@Bean
@SentinelRestTemplate(urlCleaner = "cln")
RestTemplate restTemplate() {
RestTemplate restTemplate() {
return new RestTemplate();
}
@ -321,14 +307,14 @@ public class SentinelRestTemplateTests {
public static class TestConfig12 {
@Bean
SentinelBeanPostProcessor sentinelBeanPostProcessor(
SentinelBeanPostProcessor sentinelBeanPostProcessor(
ApplicationContext applicationContext) {
return new SentinelBeanPostProcessor(applicationContext);
}
@Bean
@SentinelRestTemplate(urlCleanerClass = UrlCleanUtil.class)
RestTemplate restTemplate() {
RestTemplate restTemplate() {
return new RestTemplate();
}
@ -338,16 +324,14 @@ public class SentinelRestTemplateTests {
public static class TestConfig13 {
@Bean
SentinelBeanPostProcessor sentinelBeanPostProcessor(
SentinelBeanPostProcessor sentinelBeanPostProcessor(
ApplicationContext applicationContext) {
return new SentinelBeanPostProcessor(applicationContext);
}
@Bean
@SentinelRestTemplate(
urlCleanerClass = SentinelRestTemplateTests.UrlCleanUtil.class,
urlCleaner = "clean1")
RestTemplate restTemplate() {
@SentinelRestTemplate(urlCleanerClass = UrlCleanUtil.class, urlCleaner = "clean1")
RestTemplate restTemplate() {
return new RestTemplate();
}
@ -357,16 +341,14 @@ public class SentinelRestTemplateTests {
public static class TestConfig14 {
@Bean
SentinelBeanPostProcessor sentinelBeanPostProcessor(
SentinelBeanPostProcessor sentinelBeanPostProcessor(
ApplicationContext applicationContext) {
return new SentinelBeanPostProcessor(applicationContext);
}
@Bean
@SentinelRestTemplate(
urlCleanerClass = SentinelRestTemplateTests.UrlCleanUtil.class,
urlCleaner = "clean2")
RestTemplate restTemplate() {
@SentinelRestTemplate(urlCleanerClass = UrlCleanUtil.class, urlCleaner = "clean2")
RestTemplate restTemplate() {
return new RestTemplate();
}
@ -375,24 +357,24 @@ public class SentinelRestTemplateTests {
public static class ExceptionUtil {
public static SentinelClientHttpResponse handleException(HttpRequest request,
byte[] body, ClientHttpRequestExecution execution, BlockException ex) {
byte[] body, ClientHttpRequestExecution execution, BlockException ex) {
System.out.println("Oops: " + ex.getClass().getCanonicalName());
return new SentinelClientHttpResponse("Oops");
}
public static void handleException2(HttpRequest request, byte[] body,
ClientHttpRequestExecution execution, BlockException ex) {
ClientHttpRequestExecution execution, BlockException ex) {
System.out.println("Oops: " + ex.getClass().getCanonicalName());
}
public static SentinelClientHttpResponse fallbackException(HttpRequest request,
byte[] body, ClientHttpRequestExecution execution, BlockException ex) {
byte[] body, ClientHttpRequestExecution execution, BlockException ex) {
System.out.println("Oops: " + ex.getClass().getCanonicalName());
return new SentinelClientHttpResponse("Oops fallback");
}
public static void fallbackException2(HttpRequest request, byte[] body,
ClientHttpRequestExecution execution, BlockException ex) {
ClientHttpRequestExecution execution, BlockException ex) {
System.out.println("Oops: " + ex.getClass().getCanonicalName());
}

View File

@ -109,9 +109,9 @@ public class SentinelHealthIndicatorTests {
Health health = sentinelHealthIndicator.health();
assertThat(health.getStatus()).isEqualTo(Status.DOWN);
assertThat(health.getDetails().get("dashboard")).isEqualTo(
new Status(Status.DOWN.getCode(), "localhost:8080 can't be connected"));
assertThat(health.getStatus()).isEqualTo(Status.UNKNOWN);
assertThat(health.getDetails().get("dashboard")).isEqualTo(new Status(
Status.UNKNOWN.getCode(), "localhost:8080 can't be connected"));
}
@Test
@ -163,13 +163,13 @@ public class SentinelHealthIndicatorTests {
Health health = sentinelHealthIndicator.health();
assertThat(health.getStatus()).isEqualTo(Status.DOWN);
assertThat(health.getStatus()).isEqualTo(Status.UNKNOWN);
Map<String, Status> dataSourceDetailMap = (Map<String, Status>) health
.getDetails().get("dataSource");
assertThat(dataSourceDetailMap.get("ds1-sentinel-file-datasource"))
.isEqualTo(Status.UP);
assertThat(dataSourceDetailMap.get("ds2-sentinel-file-datasource"))
.isEqualTo(new Status(Status.DOWN.getCode(), "fileDataSource2 error"));
.isEqualTo(new Status(Status.UNKNOWN.getCode(), "fileDataSource2 error"));
}
}