Skip to content

Commit

Permalink
gateway
Browse files Browse the repository at this point in the history
  • Loading branch information
tanfeng112 committed Feb 11, 2020
1 parent d4eb116 commit 0dfb536
Show file tree
Hide file tree
Showing 14 changed files with 526 additions and 186 deletions.
31 changes: 31 additions & 0 deletions spring-cloud-nacos-gateway-consumer/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**
!**/src/test/**

### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache

### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr

### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/

### VS Code ###
.vscode/
84 changes: 84 additions & 0 deletions spring-cloud-nacos-gateway-consumer/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
<?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">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.gupaoedu.springcloud.gateway</groupId>
<artifactId>spring-cloud-nacos-gateway-consumer</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-cloud-nacos-gateway-consumer</name>
<description>Demo project for Spring Boot</description>

<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Greenwich.SR2</spring-cloud.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-nacos-discovery</artifactId>
<version>2.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-spring-cloud-gateway-adapter</artifactId>
<version>1.7.1</version>
</dependency>
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-transport-simple-http</artifactId>
<version>1.7.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
package com.gupaoedu.springcloud.gateway.springcloudnacosgatewayconsumer;

import com.alibaba.csp.sentinel.adapter.gateway.common.SentinelGatewayConstants;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiDefinition;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiPathPredicateItem;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiPredicateItem;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.GatewayApiDefinitionManager;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayParamFlowItem;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayRuleManager;
import com.alibaba.csp.sentinel.adapter.gateway.sc.SentinelGatewayFilter;
import com.alibaba.csp.sentinel.adapter.gateway.sc.exception.SentinelGatewayBlockExceptionHandler;
import org.springframework.beans.factory.ObjectProvider;
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;

import javax.annotation.PostConstruct;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
* 咕泡学院,只为更好的你
* 咕泡学院-Mic: 2227324689
* http://www.gupaoedu.com
**/
@Configuration
public class GatewayConfiguration {

private final List<ViewResolver> viewResolvers;
private final ServerCodecConfigurer serverCodecConfigurer;

public GatewayConfiguration(ObjectProvider<List<ViewResolver>> viewResolvers, ServerCodecConfigurer serverCodecConfigurer) {
this.viewResolvers = viewResolvers.getIfAvailable(Collections::emptyList);
this.serverCodecConfigurer = serverCodecConfigurer;
}

@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public GlobalFilter sentinelGatewayFilter(){
return new SentinelGatewayFilter();
}
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public GpSentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler(){
return new GpSentinelGatewayBlockExceptionHandler(viewResolvers,serverCodecConfigurer);
}
@PostConstruct
public void doInit(){
initGatewayRules();
initCustomizedApis();
}

private void initGatewayRules(){
Set<GatewayFlowRule> rules=new HashSet<>();
GatewayFlowRule gatewayFlowRule=new GatewayFlowRule("nacos-gateway-provider").setCount(1).setIntervalSec(1);

GatewayFlowRule customerFlowRule=new GatewayFlowRule("first_customized_api").
setResourceMode(SentinelGatewayConstants.RESOURCE_MODE_CUSTOM_API_NAME).
setCount(1).setIntervalSec(1);
rules.add(gatewayFlowRule);
rules.add(customerFlowRule);
GatewayRuleManager.loadRules(rules);
}

private void initCustomizedApis(){
Set<ApiDefinition> definitions=new HashSet<>();
ApiDefinition apiDefinition=new ApiDefinition("first_customized_api");
apiDefinition.setPredicateItems(new HashSet<ApiPredicateItem>(){{
add(new ApiPathPredicateItem().setPattern("/foo/**"));
add(new ApiPathPredicateItem().setPattern("/baz/**").setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX));
}});
definitions.add(apiDefinition);
GatewayApiDefinitionManager.loadApiDefinitions(definitions);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package com.gupaoedu.springcloud.gateway.springcloudnacosgatewayconsumer;

import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.alibaba.csp.sentinel.adapter.gateway.sc.exception.SentinelGatewayBlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.util.function.Supplier;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.codec.HttpMessageWriter;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.reactive.result.view.ViewResolver;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebExceptionHandler;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
* 咕泡学院,只为更好的你
* 咕泡学院-Mic: 2227324689
* http://www.gupaoedu.com
**/
public class GpSentinelGatewayBlockExceptionHandler implements WebExceptionHandler{
private List<ViewResolver> viewResolvers;
private List<HttpMessageWriter<?>> messageWriters;
public GpSentinelGatewayBlockExceptionHandler(List<ViewResolver> viewResolvers, ServerCodecConfigurer serverCodecConfigurer) {
this.viewResolvers = viewResolvers;
this.messageWriters = serverCodecConfigurer.getWriters();
}
private final Supplier<ServerResponse.Context> contextSupplier = () -> {
return new ServerResponse.Context() {
public List<HttpMessageWriter<?>> messageWriters() {
return GpSentinelGatewayBlockExceptionHandler.this.messageWriters;
}

public List<ViewResolver> viewResolvers() {
return GpSentinelGatewayBlockExceptionHandler.this.viewResolvers;
}
};
};
@Override
public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
if (exchange.getResponse().isCommitted()) {
return Mono.error(ex);
} else {
return !BlockException.isBlockException(ex) ? Mono.error(ex) : this.handleBlockedRequest(exchange, ex).flatMap((response) -> {
return this.writeResponse(response, exchange);
});
}
}
private Mono<ServerResponse> handleBlockedRequest(ServerWebExchange exchange, Throwable throwable) {
return GatewayCallbackManager.getBlockHandler().handleRequest(exchange, throwable);
}
private Mono<Void> writeResponse(ServerResponse response, ServerWebExchange exchange) {
ServerHttpResponse serverHttpResponse = exchange.getResponse();
serverHttpResponse.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
byte[] datas = "{\"code\":999,\"msg\":\"访问人数过多\"}".getBytes(StandardCharsets.UTF_8);
DataBuffer buffer = serverHttpResponse.bufferFactory().wrap(datas);
return serverHttpResponse.writeWith(Mono.just(buffer));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.gupaoedu.springcloud.gateway.springcloudnacosgatewayconsumer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringCloudNacosGatewayConsumerApplication {

public static void main(String[] args) {
SpringApplication.run(SpringCloudNacosGatewayConsumerApplication.class, args);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
spring:
application:
name: spring-cloud-nacos-gateway-consumer
cloud:
nacos:
discovery:
server-addr: 192.168.216.128:8848
gateway:
discovery:
locator:
enabled: false
lower-case-service-id: false
routes:
- id: nacos-gateway-provider
uri: lb://spring-cloud-nacos-gateway-provider
predicates:
- Path=/nacos/**
filters:
- StripPrefix=1
server:
port: 8888
management:
endpoint:
gateway:
enabled: true
endpoints:
web:
exposure:
include: "*"
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package com.gupaoedu.springcloud.gateway.springcloudnacosgatewayconsumer;

import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class SpringCloudNacosGatewayConsumerApplicationTests {


}
31 changes: 31 additions & 0 deletions spring-cloud-nacos-gateway-provider/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**
!**/src/test/**

### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache

### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr

### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/

### VS Code ###
.vscode/
Loading

0 comments on commit 0dfb536

Please sign in to comment.