共計 2555 個字符,預計需要花費 7 分鐘才能閱讀完成。
這篇文章主要介紹“Spring Cloud Gateway 如何構建”的相關知識,丸趣 TV 小編通過實際案例向大家展示操作過程,操作方法簡單快捷,實用性強,希望這篇“Spring Cloud Gateway 如何構建”文章能幫助大家解決問題。
構建服務端
使用 Spring Boot 構建一個簡單的 Web 應用,外界向網關發送請求后,會轉發到該應用,pom.xml 文件內容如下:
parent
groupId org.springframework.boot /groupId
artifactId spring-boot-starter-parent /artifactId
version 2.0.2.RELEASE /version
/parent
dependencies
dependency
groupId org.springframework.boot /groupId
artifactId spring-boot-starter-web /artifactId
/dependency
/dependencies
編寫啟動類與控制器,提供一個“hello”服務:
@SpringBootApplication
@RestController
public class ServerApp { public static void main(String[] args) { SpringApplication.run(ServerApp.class, args);
}
@GetMapping(/hello)
public String hello() {
System.out.println( 調用 hello 方法
return hello
}
}
ServerApp 中的 hello 方法,會返回 hello 字符串,啟動 ServerApp,默認使用 8080 端口,瀏覽器中訪問 http://localhost:8080/hello,可看到瀏覽器輸出結果。
構建網關
新建一個普通的 Maven 項目,加入 Spring Cloud Gateway 的依賴,pom.xml 內容如下:
parent
groupId org.springframework.boot /groupId
artifactId spring-boot-starter-parent /artifactId
version 2.0.0.RELEASE /version
/parent
dependencyManagement
dependencies
dependency
groupId org.springframework.cloud /groupId
artifactId spring-cloud-dependencies /artifactId
version Finchley.RC1 /version
type pom /type
scope import /scope
/dependency
/dependencies
/dependencyManagement
dependencies
dependency
groupId org.springframework.cloud /groupId
artifactId spring-cloud-starter-gateway /artifactId
/dependency
/dependencies
為網關項目加入配置文件 application.yml,修改服務器端口為 9000,配置文件內容如下:
server:
port: 9000
添加啟動類,配置一個路由定位器的 bean,代碼如下:
@SpringBootApplication
public class RouterApp { public static void main(String[] args) { SpringApplication.run(RouterApp.class, args);
}
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) { Function PredicateSpec, Route.Builder fn = new Function PredicateSpec, Route.Builder () { public Route.Builder apply(PredicateSpec t) {
t.path( /hello
return t.uri( http://localhost:8080
}
};
return builder.routes().route(fn).build();
}
}
以上代碼中,使用 Spring 容器中的 RouteLocatorBuilder bean 來創建路由定位器,調用 Builder 的 route 方法時,傳入 java.util.function.Function 實例,這是 Java8 加入的其中一個函數式接口,我們可以使用函數式編程來實現以上的代碼,下面的代碼等價于前面的代碼:
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) { return builder.routes()
.route(t - t.path( /hello)
.and()
.uri(http://localhost:8080))
.build();
}
以上的兩段代碼設定了一個路由規則,當瀏覽器訪問網關的 http://localhost:9000/hello 地址后,就會路由到 http://localhost:8080/hello。
除了可以路由到我們本例的 8080 端口外,還可以路由到其他網站,只需要改變一下 PredicateSpec 的 uri 即可,例如將.uri(http://localhost:8080) 改為.uri(“http://www.163.com”)。
關于“Spring Cloud Gateway 如何構建”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識,可以關注丸趣 TV 行業資訊頻道,丸趣 TV 小編每天都會為大家更新不同的知識點。