SpringCloud微服務網關Gateway怎么創建
這篇文章主要介紹“SpringCloud微服務網關Gateway怎么創建”的相關知識,小編通過實際案例向大家展示操作過程,操作方法簡單快捷,實用性強,希望這篇“SpringCloud微服務網關Gateway怎么創建”文章能幫助大家解決問題。
微服務網關GateWay介紹
Spring Cloud Gateway 是 Spring 體系內的一個全新項目,該項目是基于 Spring 5.0,Spring Boot 2.0 和 Project Reactor 等技術開發,它旨在為微服務架構提供一種簡單有效的統一的 API 路由管理方式。
Spring Cloud Gateway 作為 Spring Cloud 生態系統中的網關,目標是替代 Netflix Zuul,其不僅提供統一的路由方式,并且基于 Filter 鏈的方式提供了網關基本的功能,例如:安全、監控/指標和限流。
GateWay特性介紹
基于 Spring Framework 5,Project Reactor 和 Spring Boot 2.0
動態路由
Predicates 和 Filters 作用于特定路由
集成 Hystrix 斷路器
集成 Spring Cloud DiscoveryClient
易于編寫的 Predicates 和 Filters
限流
路徑重寫
Gateway 中的相關術語
Route(路由):這是網關的基本構建塊。它由一個 ID,一個目標 URI,一組斷言和一組過濾器定義。如果斷言為真,則路由匹配。
Predicate(斷言):這是一個 Java 8 的 Predicate。輸入類型是一個 ServerWebExchange。我們可以使用它來匹配來自 HTTP 請求的任何內容,例如 headers 或參數。
Filter(過濾器):這是
org.springframework.cloud.gateway.filter.GatewayFilter
的實例,我們可以使用它修改請求和響應。
Gateway實戰
1、創建項目gateway
創建子模塊gateway ,pom.xml引入eureka-client 和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>
2、創建啟動類
@EnableEurekaClient @SpringBootApplication public?class?GateWayApplication?{ ????public?static?void?main(String[]?args)?{ ????????SpringApplication.run(GateWayApplication.class,?args); ????} }
啟動類上增加@EnableEurekaClient以及@SpringBootApplication注解。
3、新增配置文件
新增配置文件application.yml
server:
? port: 8004
spring:
? application:
? ? name: gateway
? cloud:
? ? gateway:
? ? ? discovery:
? ? ? ? locator:
? ? ? ? ? enabled: true
? ? ? ? ? lower-case-service-id: true
? ? ? routes:
? ? ? ? - id: eureka-client-app-1
? ? ? ? ? uri: lb://app
? ? ? ? ? predicates:
? ? ? ? ? ? - Path=/**
eureka:
? client:
? ? service-url:
? ? ? defaultZone: http://localhost:8001/eureka/
spring.cloud.gateway.routes路由參數配置說明:
id:我們自定義的路由 ID。
uri:需要轉發的目標服務地址。
predicates:路由條件。
filters:過濾規則,本示例暫時沒用。
4、編程方式實現路由
上面路由規則我們也可以使用編程方式來實現,在啟動類中增加如下代碼,是等效的:
@Configuration public?class?GatewayConfig?{ ????@Bean ????public?RouteLocator?customRouteLocator(RouteLocatorBuilder?builder)?{ ????????RouteLocatorBuilder.Builder?routes?=?builder.routes(); ????????routes.route("eureka-client-app-1",r?->?r.path("/**") ???????????????.uri("lb://app")) ????????????????.build(); ????????return?routes.build(); ????} }
5、啟動驗證
訪問Gateway服務的地址:http://localhost:8004/app/index,效果如下:
關于“SpringCloud微服務網關Gateway怎么創建”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識,可以關注蝸牛博客行業資訊頻道,小編每天都會為大家更新不同的知識點。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:niceseo99@gmail.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。
評論