網(wǎng)關(guān)可以將服務(wù)和外網(wǎng)進(jìn)行隔離起到一定的保護(hù)作用,同時服務(wù)間局域網(wǎng)通信更加便捷。而且在網(wǎng)關(guān)中可以做到限流,權(quán)限校驗(yàn),使得服務(wù)更加專注自身的業(yè)務(wù)。比如說下單需要登錄權(quán)限。
spring cloud Gateway 工作原理

客戶端向spring cloud Gateway發(fā)送請求,如果請求與網(wǎng)關(guān)程序定義的路由匹配,則將其發(fā)送到網(wǎng)關(guān)web處理程序,此處理程序運(yùn)行特定的請求過濾鏈
過濾器之間用虛線分開的原因是過濾器可能會在發(fā)送代理請求之前或者之后執(zhí)行邏輯。所有"pre"過濾器先執(zhí)行,然后執(zhí)行代理請求,代理請求完成后,執(zhí)行post 過濾器邏輯。
項(xiàng)目構(gòu)成
項(xiàng)目 端口 描述
gateway-eureka-server 8080 服務(wù)注冊與發(fā)現(xiàn)
gateway-service 8081 服務(wù)
gateway-client 8082 網(wǎng)關(guān) 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>
啟動項(xiàng)
@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 項(xiàng)目
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/
創(chuàng)建類控制器 HelloWorldController ,http://localhost:8081/user/who
@RequestMapping("/user")
@RestController
public class HelloWorldController{
@RequestMapping("who")
public String helloworld() {
return "my name is liangwang";
}
}
創(chuàng)建類控制器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項(xiàng)目
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進(jìn)行路由轉(zhuǎn)發(fā),將請求進(jìn)行處理,最后轉(zhuǎn)發(fā)到目標(biāo)的下游服務(wù)
@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/的時候,網(wǎng)關(guān)轉(zhuǎn)發(fā)到
http://gateway-service:8081/order/, gateway-service服務(wù)在eureka中有注冊,最終對應(yīng)的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代表從注冊中心獲取服務(wù)),后面接的就是你需要轉(zhuǎn)發(fā)到的服務(wù)名稱
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代表從注冊中心獲取服務(wù)),后面接的就是你需要轉(zhuǎn)發(fā)到的服務(wù)名稱,按照上面的配置是http://localhost:8083/user/** => http://gateway-service:8081/user/** 到此項(xiàng)目搭建完成,接下來進(jìn)行測試,依次啟動gateway-eureka-server ,gateway-service, gateway-client
訪問;
不啟用注冊中心
即使集成了eureka-client也可以不使用注冊中心,可以關(guān)閉
eureka.client.enabled=false
StripPreffix屬性的使用
按照上面的配置,每一個路由只能對應(yīng)有個控制器的轉(zhuǎn)發(fā),不夠靈活,假如想讓userapi的請求都轉(zhuǎn)發(fā)到gateway-service 服務(wù),比如:
-
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代表從注冊中心獲取服務(wù)),后面接的就是你需要轉(zhuǎn)發(fā)到的服務(wù)名稱
predicates:
- Path=/userapi/** #userapi
filters:
- StripPrefix=1 # 表示在轉(zhuǎn)發(fā)時去掉userapi
修改完配置,重啟:
使用Hystrix
在gateway-client項(xiàng)目中引入依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
在spring cloud gateway中可以使用hystrix。Hystrix 是spring cloud 中一個服務(wù)熔斷降級的組件,在微服務(wù)系統(tǒng)有著十分重要的作用。
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項(xiàng)目,并關(guān)閉service-one服務(wù),在瀏覽器訪問
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代表從注冊中心獲取服務(wù)),后面接的就是你需要轉(zhuǎn)發(fā)到的服務(wù)名稱
predicates:
- Path=/userapi/**
filters:
- StripPrefix=1 # 表示在轉(zhuǎn)發(fā)時去掉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,當(dāng)發(fā)生錯誤時會轉(zhuǎn)發(fā)到 fallbackUri, 測試訪問 http://localhost:8083/userapi2/order/info
reference
Hystrix wiki
Spring Cloud Gateway
Redis RateLimiter
轉(zhuǎn)載Redis RateLimiter實(shí)現(xiàn)
轉(zhuǎn)載Spring Cloud Gateway 基礎(chǔ)使用