网关可以将服务和外网进行隔离起到一定的保护作用,同时服务间局域网通信更加便捷。而且在网关中可以做到限流,权限校验,使得服务更加专注自身的业务。比如说下单需要登录权限。
spring cloud Gateway 工作原理
客户端向spring cloud Gateway发送请求,如果请求与网关程序定义的路由匹配,则将其发送到网关web处理程序,此处理程序运行特定的请求过滤链
过滤器之间用虚线分开的原因是过滤器可能会在发送代理请求之前或者之后执行逻辑。所有"pre"过滤器先执行,然后执行代理请求,代理请求完成后,执行post 过滤器逻辑。
项目构成
项目 端口 描述
gateway-eureka-server 8080 服务注册与发现
gateway-service 8081 服务
gateway-client 8082 网关 gateway
gateway-eureka-server
pom文件
<?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 http://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.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.taotao</groupId>
<artifactId>eureka-server</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>eureka-server</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Greenwich.RELEASE</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</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>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
</project>
启动项
@EnableEurekaServer
@SpringBootApplication
public class GatewayEurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
配置文件 application.yml
spring:
application:
name: gateway-eureka-server
server:
port: 8080
eureka:
instance:
hostname: localhostname
client:
fetch-registry: false
register-with-eureka: false
service-url:
defaultZone: http://localhost:8080/eureka/
访问http://localhost:8080 注册中心
gateway-service 项目
pom文件,
<?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 http://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.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.taotao</groupId>
<artifactId>service-one</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>service-one</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Greenwich.RELEASE</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</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>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
</project>
启动类
@EnableEurekaClient
@SpringBootApplication
public class GatewayServiceApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceOneApplication.class, args);
}
}
配置文件 application.yml
spring:
application:
name: gateway-service
server:
port: 8081
eureka:
client:
service-url:
defaultZone: http://localhost:8080/eureka/
创建类控制器 HelloWorldController ,http://localhost:8081/user/who
@RequestMapping("/user")
@RestController
public class HelloWorldController{
@RequestMapping("who")
public String helloworld() {
return "my name is liangwang";
}
}
创建类控制器OrderController, http://localhost:8081/order/info
@RequestMapping("/order")
@RestController
public class OrderController {
@RequestMapping("/info")
public String orderInfo() {
return "order info date : " + new Date().toString();
}
}
gateway-client项目
pom文件
<?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 http://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.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.taotao</groupId>
<artifactId>gateway-client</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>gateway-client</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Greenwich.RELEASE</spring-cloud.version>
</properties>
<dependencies>
<!--使用gateway-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!---使用断路器-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</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>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
</project>
使用RouteLocator的Bean进行路由转发,将请求进行处理,最后转发到目标的下游服务
@SpringBootApplication
public class GatewayClientApplication {
@Value("${test.uri}")
private String uri;
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
return builder.routes()
//basic proxy
.route(r -> r.path("/order/**")
.uri(uri)
).build();
}
public static void main(String[] args) {
SpringApplication.run(GatewayClientApplication.class, args);
}
}
上面的代码里是访问http://localhost:8083/order/的时候,网关转发到
http://gateway-service:8081/order/, gateway-service服务在eureka中有注册,最终对应的ip: port
使用配置文件
application.yml
test:
uri: lb://gateway-service
spring:
application:
name: gateway-client
cloud:
gateway:
routes:
- id: route_service_one
uri: ${test.uri} # uri以lb://开头(lb代表从注册中心获取服务),后面接的就是你需要转发到的服务名称
predicates:
- Path=/user/**
server:
port: 8083
logging:
level:
org.springframework.cloud.gateway: TRACE
org.springframework.http.server.reactive: DEBUG
org.springframework.web.reactive: DEBUG
reactor.ipc.netty: DEBUG
eureka:
client:
service-url:
defaultZone: http://localhost:8080/eureka/
instance:
prefer-ip-address: true
其中test.uri是自我定义的属性: uri以lb://开头(lb代表从注册中心获取服务),后面接的就是你需要转发到的服务名称,按照上面的配置是http://localhost:8083/user/** => http://gateway-service:8081/user/** 到此项目搭建完成,接下来进行测试,依次启动gateway-eureka-server ,gateway-service, gateway-client
访问;
不启用注册中心
即使集成了eureka-client也可以不使用注册中心,可以关闭
eureka.client.enabled=false
StripPreffix属性的使用
按照上面的配置,每一个路由只能对应有个控制器的转发,不够灵活,假如想让userapi的请求都转发到gateway-service 服务,比如:
-
http://localhost:8083/userapi/user/who => http://localhost:8081/user/who* http://localhost:8083/userapi/order/info => http://localhost:8081/order/info
在路由配置上增加 stripPrefix=1
spring:
application:
name: gateway-client
cloud:
gateway:
routes:
- id: route_service_one
uri: ${test.uri} # uri以lb://开头(lb代表从注册中心获取服务),后面接的就是你需要转发到的服务名称
predicates:
- Path=/userapi/** #userapi
filters:
- StripPrefix=1 # 表示在转发时去掉userapi
修改完配置,重启:
使用Hystrix
在gateway-client项目中引入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
在spring cloud gateway中可以使用hystrix。Hystrix 是spring cloud 中一个服务熔断降级的组件,在微服务系统有着十分重要的作用。
Hystrix是 spring cloud gateway中是以filter的形式使用的,代码如下:
@SpringBootApplication
public class GatewayClientApplication {
@Value("${test.uri}")
private String uri;
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
return builder.routes()
//basic proxy
.route(r -> r.path("/order/**")
.uri(uri)
)
.route(r -> r.path("/user/**")
.filters(f -> f
.hystrix(config -> config
.setName("myserviceOne")
.setFallbackUri("forward:/user/fallback")))
.uri(uri)).build();
}
public static void main(String[] args) {
SpringApplication.run(GatewayClientApplication.class, args);
}
}
上面代码中添加了一个路由并配置了hystrix的fallbackUri,新增加一个FallbackController控制器
@RestController
public class FallBackController {
@RequestMapping("/user/fallback")
public Mono<String> fallback() {
return Mono.just("service error, jump fallback");
}
}
重启gateway-client项目,并关闭service-one服务,在浏览器访问
http://localhost:8083/user/who
使用yml 配置Hystrix
spring:
application:
name: gateway-client
cloud:
gateway:
routes:
- id: route_service_one
uri: ${test.uri} # uri以lb://开头(lb代表从注册中心获取服务),后面接的就是你需要转发到的服务名称
predicates:
- Path=/userapi/**
filters:
- StripPrefix=1 # 表示在转发时去掉userapi
- id: userapi2_route
uri: ${test.uri}
predicates:
- Path=/userapi2/**
filters:
- StripPrefix=1
- name: Hystrix
args:
name: myfallbackcmd
fallbackUri: forward:/user/fallback
在配置中增加了一个新的路由userapi2_route,还配置了Hystrix,当发生错误时会转发到 fallbackUri, 测试访问 http://localhost:8083/userapi2/order/info
reference
Hystrix wiki
Spring Cloud Gateway
Redis RateLimiter
转载Redis RateLimiter实现
转载Spring Cloud Gateway 基础使用