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; 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() { public boolean isEager() {
return eager; return eager;
} }
@ -218,9 +232,8 @@ public class SentinelProperties {
private String blockPage; private String blockPage;
@Deprecated @Deprecated
@DeprecatedConfigurationProperty( @DeprecatedConfigurationProperty(reason = "replaced to SentinelProperties#blockPage.", replacement = SentinelConstants.PROPERTY_PREFIX
reason = "replaced to SentinelProperties#blockPage.", + ".block-page")
replacement = SentinelConstants.PROPERTY_PREFIX + ".block-page")
public String getBlockPage() { public String getBlockPage() {
return blockPage; return blockPage;
} }

View File

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

View File

@ -77,16 +77,14 @@ public class SentinelWebFluxAutoConfiguration {
@Bean @Bean
@Order(-2) @Order(-2)
@ConditionalOnProperty(name = "spring.cloud.sentinel.filter.enabled", @ConditionalOnProperty(name = "spring.cloud.sentinel.filter.enabled", matchIfMissing = true)
matchIfMissing = true)
public SentinelBlockExceptionHandler sentinelBlockExceptionHandler() { public SentinelBlockExceptionHandler sentinelBlockExceptionHandler() {
return new SentinelBlockExceptionHandler(viewResolvers, serverCodecConfigurer); return new SentinelBlockExceptionHandler(viewResolvers, serverCodecConfigurer);
} }
@Bean @Bean
@Order(-1) @Order(-1)
@ConditionalOnProperty(name = "spring.cloud.sentinel.filter.enabled", @ConditionalOnProperty(name = "spring.cloud.sentinel.filter.enabled", matchIfMissing = true)
matchIfMissing = true)
public SentinelWebFluxFilter sentinelWebFluxFilter() { public SentinelWebFluxFilter sentinelWebFluxFilter() {
log.info("[Sentinel Starter] register Sentinel SentinelWebFluxFilter"); log.info("[Sentinel Starter] register Sentinel SentinelWebFluxFilter");
return new 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.block.flow.param.ParamFlowRule;
import com.alibaba.csp.sentinel.slots.system.SystemRule; import com.alibaba.csp.sentinel.slots.system.SystemRule;
import com.alibaba.csp.sentinel.transport.config.TransportConfig; 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.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper; import com.fasterxml.jackson.dataformat.xml.XmlMapper;
@ -79,9 +78,9 @@ public class SentinelAutoConfiguration {
System.setProperty(LogBase.LOG_NAME_USE_PID, System.setProperty(LogBase.LOG_NAME_USE_PID,
String.valueOf(properties.getLog().isSwitchPid())); 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)) { && 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)) if (StringUtils.isEmpty(System.getProperty(TransportConfig.SERVER_PORT))
&& StringUtils.hasText(properties.getTransport().getPort())) { && StringUtils.hasText(properties.getTransport().getPort())) {
@ -146,8 +145,7 @@ public class SentinelAutoConfiguration {
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
@ConditionalOnClass(name = "org.springframework.web.client.RestTemplate") @ConditionalOnClass(name = "org.springframework.web.client.RestTemplate")
@ConditionalOnProperty(name = "resttemplate.sentinel.enabled", havingValue = "true", @ConditionalOnProperty(name = "resttemplate.sentinel.enabled", havingValue = "true", matchIfMissing = true)
matchIfMissing = true)
public SentinelBeanPostProcessor sentinelBeanPostProcessor( public SentinelBeanPostProcessor sentinelBeanPostProcessor(
ApplicationContext applicationContext) { ApplicationContext applicationContext) {
return new SentinelBeanPostProcessor(applicationContext); return new SentinelBeanPostProcessor(applicationContext);
@ -156,8 +154,8 @@ public class SentinelAutoConfiguration {
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public SentinelDataSourceHandler sentinelDataSourceHandler( public SentinelDataSourceHandler sentinelDataSourceHandler(
DefaultListableBeanFactory beanFactory, SentinelProperties sentinelProperties, DefaultListableBeanFactory beanFactory, SentinelProperties sentinelProperties,
Environment env) { Environment env) {
return new SentinelDataSourceHandler(beanFactory, sentinelProperties, env); return new SentinelDataSourceHandler(beanFactory, sentinelProperties, env);
} }

View File

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

View File

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

View File

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

View File

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

View File

@ -17,6 +17,7 @@
package com.alibaba.cloud.sentinel.endpoint; package com.alibaba.cloud.sentinel.endpoint;
import java.util.HashMap; import java.util.HashMap;
import java.util.List;
import java.util.Map; import java.util.Map;
import com.alibaba.cloud.sentinel.SentinelProperties; 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.heartbeat.HeartbeatSenderProvider;
import com.alibaba.csp.sentinel.transport.HeartbeatSender; import com.alibaba.csp.sentinel.transport.HeartbeatSender;
import com.alibaba.csp.sentinel.transport.config.TransportConfig; 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.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.boot.actuate.health.AbstractHealthIndicator; import org.springframework.boot.actuate.health.AbstractHealthIndicator;
import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator; import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.boot.actuate.health.Status; 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 * A {@link HealthIndicator} for Sentinel, which checks the status of Sentinel Dashboard
@ -61,7 +63,7 @@ public class SentinelHealthIndicator extends AbstractHealthIndicator {
private SentinelProperties sentinelProperties; private SentinelProperties sentinelProperties;
public SentinelHealthIndicator(DefaultListableBeanFactory beanFactory, public SentinelHealthIndicator(DefaultListableBeanFactory beanFactory,
SentinelProperties sentinelProperties) { SentinelProperties sentinelProperties) {
this.beanFactory = beanFactory; this.beanFactory = beanFactory;
this.sentinelProperties = sentinelProperties; this.sentinelProperties = sentinelProperties;
} }
@ -74,7 +76,7 @@ public class SentinelHealthIndicator extends AbstractHealthIndicator {
// detail // detail
if (!sentinelProperties.isEnabled()) { if (!sentinelProperties.isEnabled()) {
detailMap.put("enabled", false); detailMap.put("enabled", false);
withDetails(builder.up(), detailMap); builder.up().withDetails(detailMap);
return; return;
} }
@ -82,8 +84,9 @@ public class SentinelHealthIndicator extends AbstractHealthIndicator {
// Check health of Dashboard // Check health of Dashboard
boolean dashboardUp = true; boolean dashboardUp = true;
String consoleServer = TransportConfig.getConsoleServer(); List<Tuple2<String, Integer>> consoleServerList = TransportConfig
if (StringUtils.isEmpty(consoleServer)) { .getConsoleServerList();
if (CollectionUtils.isEmpty(consoleServerList)) {
// If Dashboard isn't configured, it's OK and mark the status of Dashboard // If Dashboard isn't configured, it's OK and mark the status of Dashboard
// with UNKNOWN. // with UNKNOWN.
detailMap.put("dashboard", detailMap.put("dashboard",
@ -101,8 +104,10 @@ public class SentinelHealthIndicator extends AbstractHealthIndicator {
else { else {
// If failed to send heartbeat message, means that the Dashboard is DOWN // If failed to send heartbeat message, means that the Dashboard is DOWN
dashboardUp = false; dashboardUp = false;
detailMap.put("dashboard", new Status(Status.DOWN.getCode(), detailMap.put("dashboard",
consoleServer + " can't be connected")); 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 // DOWN
dataSourceUp = false; dataSourceUp = false;
dataSourceDetailMap.put(dataSourceBeanName, 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 Dashboard and DataSource are both OK, the health status is UP
if (dashboardUp && dataSourceUp) { if (dashboardUp && dataSourceUp) {
withDetails(builder.up(), detailMap); builder.up().withDetails(detailMap);
} }
else { 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.ApplicationContext;
import org.springframework.context.ApplicationContextAware; import org.springframework.context.ApplicationContextAware;
import org.springframework.util.ReflectionUtils; import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;
/** /**
* {@link Feign.Builder} like {@link HystrixFeign.Builder}. * {@link Feign.Builder} like {@link HystrixFeign.Builder}.
@ -75,7 +76,7 @@ public final class SentinelFeign {
super.invocationHandlerFactory(new InvocationHandlerFactory() { super.invocationHandlerFactory(new InvocationHandlerFactory() {
@Override @Override
public InvocationHandler create(Target target, public InvocationHandler create(Target target,
Map<Method, MethodHandler> dispatch) { Map<Method, MethodHandler> dispatch) {
// using reflect get fallback and fallbackFactory properties from // using reflect get fallback and fallbackFactory properties from
// FeignClientFactoryBean because FeignClientFactoryBean is a package // FeignClientFactoryBean because FeignClientFactoryBean is a package
// level class, we can not use it in our package // level class, we can not use it in our package
@ -86,7 +87,11 @@ public final class SentinelFeign {
"fallback"); "fallback");
Class fallbackFactory = (Class) getFieldValue(feignClientFactoryBean, Class fallbackFactory = (Class) getFieldValue(feignClientFactoryBean,
"fallbackFactory"); "fallbackFactory");
String beanName = (String) getFieldValue(feignClientFactoryBean, "name"); String beanName = (String) getFieldValue(feignClientFactoryBean,
"contextId");
if (!StringUtils.hasText(beanName)) {
beanName = (String) getFieldValue(feignClientFactoryBean, "name");
}
Object fallbackInstance; Object fallbackInstance;
FallbackFactory fallbackFactoryInstance; FallbackFactory fallbackFactoryInstance;

View File

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

View File

@ -1,136 +1,132 @@
///* /*
// * Copyright 2013-2018 the original author or authors. * Copyright 2013-2018 the original author or authors.
// * *
// * Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
// * you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
// * You may obtain a copy of the License at * You may obtain a copy of the License at
// * *
// * https://www.apache.org/licenses/LICENSE-2.0 * https://www.apache.org/licenses/LICENSE-2.0
// * *
// * Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
// * distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// * See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
// * limitations under the License. * limitations under the License.
// */ */
//
//package com.alibaba.cloud.sentinel; package com.alibaba.cloud.sentinel;
//
//import com.alibaba.cloud.sentinel.feign.SentinelFeignAutoConfiguration; import com.alibaba.cloud.sentinel.feign.SentinelFeignAutoConfiguration;
//import org.junit.Test; import org.junit.Test;
//import org.junit.runner.RunWith; import org.junit.runner.RunWith;
//
//import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
//import org.springframework.boot.autoconfigure.ImportAutoConfiguration; import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
//import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
//import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.cloud.openfeign.EnableFeignClients;
//import org.springframework.cloud.openfeign.FeignClient; import org.springframework.cloud.openfeign.FeignClient;
//import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
//import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit4.SpringRunner;
//import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
//import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
//import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
//
//import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
//
///** /**
// * Add this unit test to verify https://github.com/alibaba/spring-cloud-alibaba/pull/838. * Add this unit test to verify https://github.com/alibaba/spring-cloud-alibaba/pull/838.
// * *
// * @author <a href="mailto:fangjian0423@gmail.com">Jim</a> * @author <a href="mailto:fangjian0423@gmail.com">Jim</a>
// */ */
//@RunWith(SpringRunner.class) @RunWith(SpringRunner.class)
//@SpringBootTest(classes = { ContextIdSentinelFeignTests.TestConfig.class }, @SpringBootTest(classes = { ContextIdSentinelFeignTests.TestConfig.class }, properties = {
// properties = { "feign.sentinel.enabled=true" }) "feign.sentinel.enabled=true" })
//public class ContextIdSentinelFeignTests { public class ContextIdSentinelFeignTests {
//
// @Autowired @Autowired
// private EchoService echoService; private EchoService echoService;
//
// @Autowired @Autowired
// private FooService fooService; private FooService fooService;
//
// @Test @Test
// public void testFeignClient() { public void testFeignClient() {
// assertThat(echoService.echo("test")).isEqualTo("echo fallback"); assertThat(echoService.echo("test")).isEqualTo("echo fallback");
// assertThat(fooService.echo("test")).isEqualTo("foo fallback"); assertThat(fooService.echo("test")).isEqualTo("foo fallback");
// assertThat(fooService.toString()).isNotEqualTo(echoService.toString()); assertThat(fooService.toString()).isNotEqualTo(echoService.toString());
// assertThat(fooService.hashCode()).isNotEqualTo(echoService.hashCode()); assertThat(fooService.hashCode()).isNotEqualTo(echoService.hashCode());
// assertThat(echoService.equals(fooService)).isEqualTo(Boolean.FALSE); assertThat(echoService.equals(fooService)).isEqualTo(Boolean.FALSE);
// } }
//
// @Configuration @Configuration
// @EnableAutoConfiguration @EnableAutoConfiguration
// @ImportAutoConfiguration({ SentinelFeignAutoConfiguration.class }) @ImportAutoConfiguration({ SentinelFeignAutoConfiguration.class })
// @EnableFeignClients @EnableFeignClients
// public static class TestConfig { public static class TestConfig {
//
// } }
//
// @FeignClient(name = "service-provider", @FeignClient(contextId = "echoService", name = "service-provider", fallback = EchoServiceFallback.class, configuration = FeignConfiguration.class)
// fallback = EchoServiceFallback.class, public interface EchoService {
// configuration = FeignConfiguration.class)
// public interface EchoService { @GetMapping("/echo/{str}")
// String echo(@PathVariable("str") String str);
// @GetMapping("/echo/{str}")
// String echo(@PathVariable("str") String str); }
//
// } @FeignClient(contextId = "fooService", value = "foo-service", fallbackFactory = CustomFallbackFactory.class, configuration = FeignConfiguration.class)
// public interface FooService {
// @FeignClient(value = "foo-service",
// fallbackFactory = CustomFallbackFactory.class, @RequestMapping(path = "echo/{str}")
// configuration = FeignConfiguration.class) String echo(@RequestParam("str") String param);
// public interface FooService {
// }
// @RequestMapping(path = "echo/{str}")
// String echo(@RequestParam("str") String param); public static class FeignConfiguration {
//
// } @Bean
// public EchoServiceFallback echoServiceFallback() {
// public static class FeignConfiguration { return new EchoServiceFallback();
// }
// @Bean
// public EchoServiceFallback echoServiceFallback() { @Bean
// return new EchoServiceFallback(); public CustomFallbackFactory customFallbackFactory() {
// } return new CustomFallbackFactory();
// }
// @Bean
// public CustomFallbackFactory customFallbackFactory() { }
// return new CustomFallbackFactory();
// } public static class EchoServiceFallback implements EchoService {
//
// } @Override
// public String echo(@RequestParam("str") String param) {
// public static class EchoServiceFallback implements EchoService { return "echo fallback";
// }
// @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) {
// public static class FooServiceFallback implements FooService { return "foo fallback";
// }
// @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();
// public static class CustomFallbackFactory
// implements feign.hystrix.FallbackFactory<FooService> { @Override
// public FooService create(Throwable throwable) {
// private FooService fooService = new FooServiceFallback(); return fooService;
// }
// @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.log.LogBase;
import com.alibaba.csp.sentinel.slots.block.BlockException; import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant; 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.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager; import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.csp.sentinel.transport.config.TransportConfig; import com.alibaba.csp.sentinel.transport.config.TransportConfig;
import com.alibaba.csp.sentinel.util.function.Tuple2;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
@ -64,8 +63,9 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
* @author jiashuai.xie * @author jiashuai.xie
*/ */
@RunWith(SpringRunner.class) @RunWith(SpringRunner.class)
@SpringBootTest(classes = { SentinelAutoConfigurationTests.TestConfig.class }, @SpringBootTest(classes = {
properties = { "spring.cloud.sentinel.filter.order=123", SentinelAutoConfigurationTests.TestConfig.class }, properties = {
"spring.cloud.sentinel.filter.order=123",
"spring.cloud.sentinel.filter.urlPatterns=/*,/test", "spring.cloud.sentinel.filter.urlPatterns=/*,/test",
"spring.cloud.sentinel.metric.fileSingleSize=9999", "spring.cloud.sentinel.metric.fileSingleSize=9999",
"spring.cloud.sentinel.metric.fileTotalCount=100", "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.flow.coldFactor=3",
"spring.cloud.sentinel.eager=true", "spring.cloud.sentinel.eager=true",
"spring.cloud.sentinel.log.switchPid=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.port=9999",
"spring.cloud.sentinel.transport.clientIp=1.1.1.1", "spring.cloud.sentinel.transport.clientIp=1.1.1.1",
"spring.cloud.sentinel.transport.heartbeatIntervalMs=20000" }, "spring.cloud.sentinel.transport.heartbeatIntervalMs=20000" }, webEnvironment = RANDOM_PORT)
webEnvironment = RANDOM_PORT)
public class SentinelAutoConfigurationTests { public class SentinelAutoConfigurationTests {
@Autowired @Autowired
@ -115,13 +114,6 @@ public class SentinelAutoConfigurationTests {
rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT); rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);
rule.setStrategy(RuleConstant.STRATEGY_DIRECT); rule.setStrategy(RuleConstant.STRATEGY_DIRECT);
FlowRuleManager.loadRules(Arrays.asList(rule)); 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 @Test
@ -142,7 +134,9 @@ public class SentinelAutoConfigurationTests {
Map<String, Object> map = sentinelEndpoint.invoke(); Map<String, Object> map = sentinelEndpoint.invoke();
assertThat(map.get("logUsePid")).isEqualTo(Boolean.TRUE); 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("clientPort")).isEqualTo("9999");
assertThat(map.get("heartbeatIntervalMs")).isEqualTo(20000L); assertThat(map.get("heartbeatIntervalMs")).isEqualTo(20000L);
assertThat(map.get("clientIp")).isEqualTo("1.1.1.1"); assertThat(map.get("clientIp")).isEqualTo("1.1.1.1");
@ -174,7 +168,7 @@ public class SentinelAutoConfigurationTests {
private void checkSentinelTransport() { private void checkSentinelTransport() {
assertThat(sentinelProperties.getTransport().getPort()).isEqualTo("9999"); assertThat(sentinelProperties.getTransport().getPort()).isEqualTo("9999");
assertThat(sentinelProperties.getTransport().getDashboard()) 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().getClientIp()).isEqualTo("1.1.1.1");
assertThat(sentinelProperties.getTransport().getHeartbeatIntervalMs()) assertThat(sentinelProperties.getTransport().getHeartbeatIntervalMs())
.isEqualTo("20000"); .isEqualTo("20000");
@ -191,7 +185,9 @@ public class SentinelAutoConfigurationTests {
@Test @Test
public void testSentinelSystemProperties() { public void testSentinelSystemProperties() {
assertThat(LogBase.isLogNameUsePid()).isEqualTo(true); 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.getPort()).isEqualTo("9999");
assertThat(TransportConfig.getHeartbeatIntervalMs().longValue()) assertThat(TransportConfig.getHeartbeatIntervalMs().longValue())
.isEqualTo(20000L); .isEqualTo(20000L);
@ -203,7 +199,7 @@ public class SentinelAutoConfigurationTests {
} }
@Test @Test
public void testFlowRestTemplate() { public void testRestTemplateBlockHandler() {
assertThat(restTemplate.getInterceptors().size()).isEqualTo(2); assertThat(restTemplate.getInterceptors().size()).isEqualTo(2);
assertThat(restTemplateWithBlockClass.getInterceptors().size()).isEqualTo(1); assertThat(restTemplateWithBlockClass.getInterceptors().size()).isEqualTo(1);
@ -231,42 +227,31 @@ public class SentinelAutoConfigurationTests {
}).isInstanceOf(RestClientException.class); }).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 @Configuration
static class SentinelTestConfiguration { static class SentinelTestConfiguration {
@Bean @Bean
@SentinelRestTemplate @SentinelRestTemplate
RestTemplate restTemplate() { RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate(); RestTemplate restTemplate = new RestTemplate();
restTemplate.getInterceptors().add(mock(ClientHttpRequestInterceptor.class)); restTemplate.getInterceptors().add(mock(ClientHttpRequestInterceptor.class));
return restTemplate; return restTemplate;
} }
@Bean @Bean
@SentinelRestTemplate(blockHandlerClass = ExceptionUtil.class, @SentinelRestTemplate(blockHandlerClass = ExceptionUtil.class, blockHandler = "handleException")
blockHandler = "handleException") RestTemplate restTemplateWithBlockClass() {
RestTemplate restTemplateWithBlockClass() {
return new RestTemplate(); return new RestTemplate();
} }
@Bean @Bean
@SentinelRestTemplate(fallbackClass = ExceptionUtil.class, @SentinelRestTemplate(fallbackClass = ExceptionUtil.class, fallback = "fallbackException")
fallback = "fallbackException") RestTemplate restTemplateWithFallbackClass() {
RestTemplate restTemplateWithFallbackClass() {
return new RestTemplate(); return new RestTemplate();
} }
@Bean @Bean
RestTemplate restTemplateWithoutBlockClass() { RestTemplate restTemplateWithoutBlockClass() {
return new RestTemplate(); return new RestTemplate();
} }
@ -275,13 +260,13 @@ public class SentinelAutoConfigurationTests {
public static class ExceptionUtil { public static class ExceptionUtil {
public static SentinelClientHttpResponse handleException(HttpRequest request, 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()); System.out.println("Oops: " + ex.getClass().getCanonicalName());
return new SentinelClientHttpResponse("Oops"); return new SentinelClientHttpResponse("Oops");
} }
public static SentinelClientHttpResponse fallbackException(HttpRequest request, 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()); System.out.println("Oops: " + ex.getClass().getCanonicalName());
return new SentinelClientHttpResponse("Oops fallback"); 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> * @author <a href="mailto:fangjian0423@gmail.com">Jim</a>
*/ */
@RunWith(SpringRunner.class) @RunWith(SpringRunner.class)
@SpringBootTest(classes = { SentinelBeanAutowiredTests.TestConfig.class }, @SpringBootTest(classes = { SentinelBeanAutowiredTests.TestConfig.class }, properties = {
properties = { "spring.cloud.sentinel.filter.order=111" }) "spring.cloud.sentinel.filter.order=111" })
public class SentinelBeanAutowiredTests { public class SentinelBeanAutowiredTests {
@Autowired @Autowired

View File

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

View File

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

View File

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