簡介:
SpringCloud Gateway的是SpringCloud的一個全新的專案,基于Spring 5.0 加SpringBoot2.0和Project Reactor等技術開發的網關,他只在為微服務架構提供一種簡單有效的API路由管理方式
SpringCloud Gateway作為SpringCloud 生態系統中的網關,目標是替代了Zull,在SpringCloud 2.0以上的版本中,沒有對新版本的Zull 2.0以上最新高性能版本進行集成,任然還是使用Zuul 1.X非Reaceor模式的老版本,而為了提升網關的的性能SpringCloud Gateway是基于WebFiux框架實作黨的,而WebFiux框架底層則使用了性能高的Reactor模式通信框架Netty
SpringCloud Gateway的目標提供統一的路由方式基于Filter鏈的方式提供了網關基本的功能,安全,監控,指標 和限流
zuul和Gateway的區別
一方面是zuul已經進入維護階段,而Gateway是SpringCloud團隊研發解決 網關的產品,有很多功能,用起來比Zuul簡單,
Gateway是基于異步非阻塞模型上開發的,性能方面優越,雖然Netrflix早就發布了Zuul二代但是一直在范訓期
Gateway的三大核心:
Route(路由):路由是構建網關的基本模塊,他由ID目標URI一系列的斷言和過濾器組
Predicate(斷言):可與匹配HTTP請求中的所有的內容比如請求頭或引數,如果請求與 斷言相匹配路由
Filetr(過濾):指的是Spring框架GatewayFiletr的實體 ,使用過濾器,可以在請求被路由前或者之后對請求修改
作業流程

客戶端 SpringCloud Gateway發出請求 ,然后再Gateway Handler Mapping中找到請求相匹配的 路由,將其轉發Gateway Web Handler
Handler 在通過指定的 過濾器鏈來將請求 發送到我們實際的服務執行邏輯,然后回傳,過濾器之間用虛線分開是因為過濾器可能會在發送代理請求(“pre”)或之后(“post”)執行業務邏輯
Filetr在“pre”型別的過濾器可以做引數校驗,權限校驗,流量監控,日志輸出,協議轉換,在post 型別的過濾器中可以做相應內容,相應頭修改 ,日志輸出,流量監控有著非常重要的作用
使用:
pom
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
創建專案路由
yml
server:
port: 8085
spring:
application:
name: cloud-gateway
cloud:
gateway:
discovery:
locator:
enabled: true #開啟從注冊中心動態創建路由的功能,利用微服務名進行路由
routes:
- id: cloud-hystrix-provider #payment_route #路由的ID,沒有固定規則但要求唯一,建議配合服務名
#lb://CLOUD-HYSTRIX-PROVIDER 等于localhost:8084的服務
uri: lb://CLOUD-HYSTRIX-PROVIDER #匹配后提供服務的路由地址
predicates:
- Path=/select/** # 斷言,路徑相匹配的進行路由
- id: cloud-hystrix-providers #payment_route #路由的ID,沒有固定規則但要求唯一,建議配合服務名
uri: lb://CLOUD-HYSTRIX-PROVIDER #匹配后提供服務的路由地址
predicates:
- Path=/getALL/** # 斷言,路徑相匹配的進行路由
#- After=2020-02-21T15:51:37.485+08:00[Asia/Shanghai]
#- Cookie=username,zzyy
#- Header=X-Request-Id, \d+ # 請求頭要有X-Request-Id屬性并且值為整數的正則運算式
eureka:
instance:
hostname: cloud-gateway-service
client:
register-with-eureka: true
fetchRegistry: true
service-url:
defaultZone: http://localhost:9001/eureka,http://127.0.0.1:9002/eureka
自定義網關(看需求)
@Component
@Slf4j
public class MyLogGateWayFilter implements GlobalFilter,Ordered
{
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain)
{
String uname = exchange.getRequest().getQueryParams().getFirst("name");
if(name == null)
{
exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
return exchange.getResponse().setComplete();
}
return chain.filter(exchange);
}
@Override
public int getOrder()
{
return 0;
}
}
主啟動類
package com.tnag.cloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableEurekaClient
public class Gateway8085 {
public static void main(String[] args) {
SpringApplication.run(Gateway8085.class,args);
}
}
配置好直接訪問測驗就可以(測驗用的 yml測驗)

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/212935.html
標籤:其他
