mirror of
https://gitee.com/mirrors/Spring-Cloud-Alibaba.git
synced 2021-06-26 13:25:11 +08:00
Polish #615, rename spring-cloud-alibaba-sentinel-zuul to spring-cloud-alibaba-sentinel-gateway
This commit is contained in:
141
spring-cloud-alibaba-sentinel-gateway/README.md
Executable file
141
spring-cloud-alibaba-sentinel-gateway/README.md
Executable file
@@ -0,0 +1,141 @@
|
||||
# Sentinel Spring Cloud Zuul Adapter
|
||||
|
||||
Zuul does not provide rateLimit function, If use default `SentinelRibbonFilter` route filter. it wrapped by Hystrix Command. so only provide Service level
|
||||
circuit protect.
|
||||
|
||||
Sentinel can provide `ServiceId` level and `API Path` level flow control for spring cloud zuul gateway service.
|
||||
|
||||
*Note*: this project is for zuul 1.
|
||||
|
||||
## How to use
|
||||
|
||||
1. Add maven dependency
|
||||
|
||||
```xml
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>
|
||||
<version>x.y.z</version>
|
||||
</dependency>
|
||||
|
||||
```
|
||||
|
||||
2. Set application.property
|
||||
|
||||
```
|
||||
// default value is false
|
||||
spring.cloud.sentinel.zuul.enabled=true
|
||||
```
|
||||
|
||||
## How it works
|
||||
|
||||
As Zuul run as per thread per connection block model, we add filters around `route Filter` to trace sentinel statistics.
|
||||
|
||||
- `SentinelPreFilter`: Get an entry of resource,the first order is **ServiceId**, then **API Path**.
|
||||
- `SentinelPostFilter`: When success response,exit entry.
|
||||
- `SentinelErrorFilter`: When get an `Exception`, trace the exception and exit context.
|
||||
|
||||
|
||||
the order of Filter can be changed by configuration:
|
||||
|
||||
```
|
||||
spring.cloud.sentinel.zuul.order.post=0
|
||||
spring.cloud.sentinel.zuul.order.pre=10000
|
||||
spring.cloud.sentinel.zuul.order.error=-1
|
||||
```
|
||||
|
||||
|
||||
Filters create structure like:
|
||||
|
||||
|
||||
```bash
|
||||
|
||||
EntranceNode: machine-root(t:3 pq:0 bq:0 tq:0 rt:0 prq:0 1mp:0 1mb:0 1mt:0)
|
||||
-EntranceNode: coke(t:2 pq:0 bq:0 tq:0 rt:0 prq:0 1mp:0 1mb:0 1mt:0)
|
||||
--coke(t:2 pq:0 bq:0 tq:0 rt:0 prq:0 1mp:0 1mb:0 1mt:0)
|
||||
---/coke/uri(t:0 pq:0 bq:0 tq:0 rt:0 prq:0 1mp:0 1mb:0 1mt:0)
|
||||
-EntranceNode: sentinel_default_context(t:0 pq:0 bq:0 tq:0 rt:0 prq:0 1mp:0 1mb:0 1mt:0)
|
||||
-EntranceNode: book(t:1 pq:0 bq:0 tq:0 rt:0 prq:0 1mp:0 1mb:0 1mt:0)
|
||||
--book(t:1 pq:0 bq:0 tq:0 rt:0 prq:0 1mp:0 1mb:0 1mt:0)
|
||||
---/book/uri(t:0 pq:0 bq:0 tq:0 rt:0 prq:0 1mp:0 1mb:0 1mt:0)
|
||||
|
||||
```
|
||||
|
||||
`book` and `coke` are serviceId.
|
||||
|
||||
`---/book/uri` is api path, the real uri is `/uri`.
|
||||
|
||||
|
||||
## Integration with Sentinel DashBord
|
||||
|
||||
Start [Sentinel DashBord](https://github.com/alibaba/Sentinel/wiki/%E6%8E%A7%E5%88%B6%E5%8F%B0).
|
||||
|
||||
## Rule config with dataSource
|
||||
|
||||
Sentinel has full rule config features. see [Dynamic-Rule-Configuration](https://github.com/alibaba/Sentinel/wiki/Dynamic-Rule-Configuration)
|
||||
|
||||
|
||||
## Custom Fallbacks
|
||||
|
||||
Implements `SentinelFallbackProvider` to define your own Fallback Provider when Sentinel Block Exception throwing for different rout. the default
|
||||
Fallback Provider is `DefaultBlockFallbackProvider`.
|
||||
|
||||
By default Fallback route is `ServiveId + URI PATH`, example `/book/coke`, first `book` is serviceId, `/uri` is URI PATH, so both
|
||||
can be needed.
|
||||
|
||||
Here is an example:
|
||||
|
||||
```java
|
||||
|
||||
// custom provider
|
||||
public class MyCokeServiceBlockFallbackProvider implements SentinelFallbackProvider {
|
||||
|
||||
private Logger logger = LoggerFactory.getLogger(DefaultBlockFallbackProvider.class);
|
||||
|
||||
// you can define root as service level
|
||||
@Override
|
||||
public String getRoute() {
|
||||
return "/coke/uri";
|
||||
}
|
||||
|
||||
@Override
|
||||
public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
|
||||
if (cause instanceof BlockException) {
|
||||
logger.info("get in fallback block exception:{}", cause);
|
||||
return response(HttpStatus.TOO_MANY_REQUESTS, route);
|
||||
} else {
|
||||
return response(HttpStatus.INTERNAL_SERVER_ERROR, route);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
## Custom Request Origin Parser
|
||||
By default this adapter use `DefaultRequestOriginParser` to parse sentinel origin.
|
||||
|
||||
```java
|
||||
|
||||
public class CustomRequestOriginParser implements RequestOriginParser {
|
||||
@Override
|
||||
public String parseOrigin(HttpServletRequest request) {
|
||||
// do custom logic.
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
## Custom UrlCleaner
|
||||
By default this adapter use `DefaultUrlCleaner` to define uri resource.
|
||||
|
||||
```java
|
||||
public class CustomUrlCleaner implements UrlCleaner {
|
||||
|
||||
@Override
|
||||
public String clean(String originUrl) {
|
||||
// do custom logic.
|
||||
return originUrl;
|
||||
}
|
||||
}
|
||||
```
|
53
spring-cloud-alibaba-sentinel-gateway/pom.xml
Normal file
53
spring-cloud-alibaba-sentinel-gateway/pom.xml
Normal file
@@ -0,0 +1,53 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<parent>
|
||||
<artifactId>spring-cloud-alibaba</artifactId>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<version>0.9.1.BUILD-SNAPSHOT</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>
|
||||
<name>Spring Cloud Alibaba Sentinel Gateway</name>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.alibaba.csp</groupId>
|
||||
<artifactId>sentinel-zuul-adapter</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.alibaba.csp</groupId>
|
||||
<artifactId>sentinel-spring-cloud-gateway-adapter</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-gateway</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-configuration-processor</artifactId>
|
||||
<scope>provided</scope>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.mockito</groupId>
|
||||
<artifactId>mockito-core</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
@@ -0,0 +1,91 @@
|
||||
/*
|
||||
* Copyright (C) 2018 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.cloud.alibaba.sentinel.gateway;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
|
||||
import com.alibaba.csp.sentinel.adapter.gateway.sc.SentinelGatewayFilter;
|
||||
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
|
||||
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
|
||||
import com.alibaba.csp.sentinel.adapter.gateway.sc.exception.SentinelGatewayBlockExceptionHandler;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.cloud.gateway.filter.GlobalFilter;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.http.codec.ServerCodecConfigurer;
|
||||
import org.springframework.web.reactive.result.view.ViewResolver;
|
||||
|
||||
/**
|
||||
* @author <a href="mailto:fangjian0423@gmail.com">Jim</a>
|
||||
*/
|
||||
@Configuration
|
||||
@ConditionalOnClass(GlobalFilter.class)
|
||||
@ConditionalOnProperty(prefix = "spring.cloud.sentinel.spring-cloud-gateway", name = "enabled", havingValue = "true",
|
||||
matchIfMissing = true)
|
||||
public class SentinelSpringCloudGatewayAutoConfiguration {
|
||||
|
||||
private static final Logger logger = LoggerFactory
|
||||
.getLogger(SentinelSpringCloudGatewayAutoConfiguration.class);
|
||||
|
||||
private final List<ViewResolver> viewResolvers;
|
||||
private final ServerCodecConfigurer serverCodecConfigurer;
|
||||
|
||||
@Autowired
|
||||
private Optional<BlockRequestHandler> blockRequestHandlerOptional;
|
||||
|
||||
@PostConstruct
|
||||
private void init() {
|
||||
blockRequestHandlerOptional
|
||||
.ifPresent(GatewayCallbackManager::setBlockHandler);
|
||||
}
|
||||
|
||||
public SentinelSpringCloudGatewayAutoConfiguration(
|
||||
ObjectProvider<List<ViewResolver>> viewResolversProvider,
|
||||
ServerCodecConfigurer serverCodecConfigurer) {
|
||||
this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
|
||||
this.serverCodecConfigurer = serverCodecConfigurer;
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Order(Ordered.HIGHEST_PRECEDENCE)
|
||||
public SentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler() {
|
||||
// Register the block exception handler for Spring Cloud Gateway.
|
||||
logger.info("[Sentinel SpringCloudGateway] register SentinelGatewayBlockExceptionHandler");
|
||||
return new SentinelGatewayBlockExceptionHandler(viewResolvers,
|
||||
serverCodecConfigurer);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Order(-1)
|
||||
public GlobalFilter sentinelGatewayFilter() {
|
||||
logger.info("[Sentinel SpringCloudGateway] register SentinelGatewayFilter");
|
||||
return new SentinelGatewayFilter();
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,115 @@
|
||||
/*
|
||||
* Copyright 1999-2018 Alibaba Group Holding Ltd.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.cloud.alibaba.sentinel.gateway;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
|
||||
import com.alibaba.csp.sentinel.adapter.gateway.zuul.callback.RequestOriginParser;
|
||||
import com.alibaba.csp.sentinel.adapter.gateway.zuul.callback.ZuulGatewayCallbackManager;
|
||||
import com.alibaba.csp.sentinel.adapter.gateway.zuul.filters.SentinelZuulErrorFilter;
|
||||
import com.alibaba.csp.sentinel.adapter.gateway.zuul.filters.SentinelZuulPostFilter;
|
||||
import com.alibaba.csp.sentinel.adapter.gateway.zuul.filters.SentinelZuulPreFilter;
|
||||
|
||||
import com.netflix.zuul.ZuulFilter;
|
||||
import com.netflix.zuul.http.ZuulServlet;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.cloud.alibaba.sentinel.gateway.handler.FallBackProviderHandler;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.env.Environment;
|
||||
|
||||
/**
|
||||
* Sentinel Spring Cloud Zuul AutoConfiguration
|
||||
*
|
||||
* @author tiger
|
||||
*/
|
||||
@Configuration
|
||||
@ConditionalOnClass(ZuulServlet.class)
|
||||
@ConditionalOnProperty(prefix = SentinelZuulAutoConfiguration.PREFIX, name = "enabled", havingValue = "true",
|
||||
matchIfMissing = true)
|
||||
public class SentinelZuulAutoConfiguration {
|
||||
|
||||
private static final Logger logger = LoggerFactory
|
||||
.getLogger(SentinelZuulAutoConfiguration.class);
|
||||
|
||||
public static final String PREFIX = "spring.cloud.sentinel.zuul";
|
||||
|
||||
@Autowired
|
||||
private Environment environment;
|
||||
|
||||
@Autowired
|
||||
private Optional<RequestOriginParser> requestOriginParserOptional;
|
||||
|
||||
@PostConstruct
|
||||
private void init() {
|
||||
requestOriginParserOptional
|
||||
.ifPresent(ZuulGatewayCallbackManager::setOriginParser);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ZuulFilter sentinelZuulPreFilter() {
|
||||
String preOrderStr = environment.getProperty(PREFIX + "." + "order.pre");
|
||||
int order = 10000;
|
||||
try {
|
||||
order = Integer.parseInt(preOrderStr);
|
||||
} catch (NumberFormatException e) {
|
||||
// ignore
|
||||
}
|
||||
logger.info("[Sentinel Zuul] register SentinelZuulPreFilter {}", order);
|
||||
return new SentinelZuulPreFilter(order);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ZuulFilter sentinelZuulPostFilter() {
|
||||
String postOrderStr = environment.getProperty(PREFIX + "." + "order.post");
|
||||
int order = 1000;
|
||||
try {
|
||||
order = Integer.parseInt(postOrderStr);
|
||||
} catch (NumberFormatException e) {
|
||||
// ignore
|
||||
}
|
||||
logger.info("[Sentinel Zuul] register SentinelZuulPostFilter {}", order);
|
||||
return new SentinelZuulPostFilter(order);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ZuulFilter sentinelZuulErrorFilter() {
|
||||
String errorOrderStr = environment.getProperty(PREFIX + "." + "order.error");
|
||||
int order = -1;
|
||||
try {
|
||||
order = Integer.parseInt(errorOrderStr);
|
||||
} catch (NumberFormatException e) {
|
||||
// ignore
|
||||
}
|
||||
logger.info("[Sentinel Zuul] register SentinelZuulErrorFilter {}", order);
|
||||
return new SentinelZuulErrorFilter(order);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public FallBackProviderHandler fallBackProviderHandler(
|
||||
DefaultListableBeanFactory beanFactory) {
|
||||
return new FallBackProviderHandler(beanFactory);
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,44 @@
|
||||
package org.springframework.cloud.alibaba.sentinel.gateway.handler;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import com.alibaba.csp.sentinel.adapter.gateway.zuul.fallback.DefaultBlockFallbackProvider;
|
||||
import com.alibaba.csp.sentinel.adapter.gateway.zuul.fallback.ZuulBlockFallbackManager;
|
||||
import com.alibaba.csp.sentinel.adapter.gateway.zuul.fallback.ZuulBlockFallbackProvider;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.SmartInitializingSingleton;
|
||||
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
/**
|
||||
* @author tiger
|
||||
*/
|
||||
public class FallBackProviderHandler implements SmartInitializingSingleton {
|
||||
|
||||
private static final Logger logger = LoggerFactory
|
||||
.getLogger(FallBackProviderHandler.class);
|
||||
|
||||
private final DefaultListableBeanFactory beanFactory;
|
||||
|
||||
public FallBackProviderHandler(DefaultListableBeanFactory beanFactory) {
|
||||
this.beanFactory = beanFactory;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterSingletonsInstantiated() {
|
||||
Map<String, ZuulBlockFallbackProvider> providerMap = beanFactory
|
||||
.getBeansOfType(ZuulBlockFallbackProvider.class);
|
||||
if (!CollectionUtils.isEmpty(providerMap)) {
|
||||
providerMap.forEach((k, v) -> {
|
||||
logger.info("[Sentinel Zuul] Register provider name:{}, instance: {}", k,
|
||||
v);
|
||||
ZuulBlockFallbackManager.registerProvider(v);
|
||||
});
|
||||
} else {
|
||||
logger.info("[Sentinel Zuul] Register default fallback provider. ");
|
||||
ZuulBlockFallbackManager.registerProvider(new DefaultBlockFallbackProvider());
|
||||
}
|
||||
}
|
||||
}
|
@@ -0,0 +1,3 @@
|
||||
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
|
||||
org.springframework.cloud.alibaba.sentinel.gateway.SentinelZuulAutoConfiguration,\
|
||||
org.springframework.cloud.alibaba.sentinel.gateway.SentinelSpringCloudGatewayAutoConfiguration
|
Reference in New Issue
Block a user