Spring Cloud Gateway是一個API網關,它是用於代替Zuul而出現的。Spring Cloud Gateway構建於Spring生態系統之上,包括Spring5,SpringBoot2等。它的目標是提供簡單、有效的方式路由你的API。java
Spring Cloud Gateway不能在傳統的Servlet容器中工做,也不能構建成一個war包工做。這一點很重要。web
Spring Cloud Gateway的流程圖以下:spring
首先咱們使用IDEA建立Spring-boot項目,並選擇spring-cloud-starter-gateway依賴,請注意,這裏千萬不能選擇spring-boot-starter-web,它們兩個不能同時存在。而後咱們在啓動類中,增長以下代碼:瀏覽器
@Bean
public RouteLocator myRoutes(RouteLocatorBuilder builder) {
return builder.routes()
.route(p -> p
.path("/get")
.filters(f -> f.addRequestHeader("Hello", "World"))
.uri("http://httpbin.org"))
.build();
}
myRoutes方法的輸入參數類型爲RouteLocatorBuilder,它能夠很是簡單的向路由中增長斷言和過濾器。上例中,咱們的斷言爲「/get」,凡是訪問路由網關中的「/get」路徑,都會在請求頭中增長「Hello」—「World」鍵值對,而且會轉發到http://httpbin.org。咱們啓動項目,並在瀏覽器中訪問http://localhost:8080/get,結果以下:app
當咱們訪問http://localhost:8080/get時,Gateway首先會判斷路徑/get,肯定路徑/get符合條件後,在請求頭中添加「Hello」—「World」。而後會轉發請求到http://httpbin.org/get,而後返回上圖的響應。框架
咱們還能夠在Gateway中,使用熔斷機制,當咱們轉發請求,獲取的響應超時(504錯誤)時,能夠喚起咱們設置的熔斷措施,並返回預設的結果。代碼以下:spring-boot
@Bean
public RouteLocator myRoutes(RouteLocatorBuilder builder) {
return builder.routes()
.route(p -> p
.path("/get")
.filters(f -> f.addRequestHeader("Hello", "World"))
.uri("http://httpbin.org:80"))
.route(p -> p
.host("*.hystrix.com")
.filters(f -> f.hystrix(config -> config
.setName("myHystrix")
.setFallbackUri("forward:/fallback")))
.uri("http://httpbin.org"))
.build();
}
@RequestMapping("fallback")
public String fallback() {
return "Hello,Hystrix fallback";
}
咱們看方法中的第二個route,斷言的判斷爲Host=*.hystrix.com,當請求頭中的Host爲*.hystrix.com,進入此路由,而後再過濾器中,設置Hystrix熔斷,當請求超時時,請求轉發到Gateway中的「/fallback」,"/fallback"咱們將返回「Hello,Hystrix fallback」。咱們啓動Gateway,並經過Postman配置請求頭Host=www.hystrix.com,訪問http://localhost:8080/delay/3。結果以下:ui
Spring Cloud Gateway就先介紹到這裏,固然它還有不少強大的功能,在這裏並無一一展開的去講。若有疑問,歡迎評論區留言哦~spa