初试Spring Cloud Gateway
构建服务端
使用Spring Boot构建一个简单的Web应用,外界向网关发送请求后,会转发到该应用,pom.xml文件内容如下:
<parent>
<groupid>org.springframework.boot
<artifactid>spring-boot-starter-parent
<version>2.0.2.RELEASE
<dependencies>
<dependency>
<groupid>org.springframework.boot
<artifactid>spring-boot-starter-web
编写启动类与控制器,提供一个“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
<artifactid>spring-boot-starter-parent
<version>2.0.0.RELEASE
<dependencymanagement>
<dependencies>
<dependency>
<groupid>org.springframework.cloud
<artifactid>spring-cloud-dependencies
<version>Finchley.RC1
<type>pom
<scope>import
<dependencies>
<dependency>
<groupid>org.springframework.cloud
<artifactid>spring-cloud-starter-gateway
为网关项目加入配置文件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> fn = new Function<predicatespec>() {
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”)。
閱讀更多 IT脫口秀 的文章