網關可以將服務和外網進行隔離起到一定的保護作用,同時服務間局域網通信更加便捷。而且在網關中可以做到限流,權限校驗,使得服務更加專注自身的業務。比如說下單需要登錄權限。
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 基礎使用