目的:我们的目的是从初学者的角度,用gateway跑helloworld
1.创建springboot工程
首先利用idea 创建springboot工程。我是先创建了一个gate-parent工程,然后删掉了src作为父工程,然后创建了一个gate-way和web的子模块。
gate-way:网关工程
web:普通的web工程
2.gate-way工程引入依赖
引入网关的依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
3.完善网关工程
配置网关工程的配置,与web工程进行关联。
spring:
cloud:
gateway:
routes:
- id: after_route #一个路由(服务)的唯一标识
uri: http://localhost:9999 #服务的地址
predicates: #过滤条件
- Cookie=mycookie,mycookievalue #必须cookie中携带mycookie=mycookievalue
server:
port: 8888
4.编写web controller
package com.example.web.action;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/hello/{name}")
public String hello(@PathVariable String name) {
return "hello " + name;
}
}
5.启动服务
通过application分别启动gate-way(8888端口)和web(9999端口)工程。
6.访问web工程
直接访问web工程: http://localhost:9999/hello/w
7. 通过网关工程访问
http://localhost:8888/hello/w
8.设置cookie之后网关访问
添加cookie之后,可以通过网关访问web工程
9.总结
到这里,我们的最简单的工程案例就完了,相信对于刚接触spring cloud gate-way的小伙伴应该还是很有帮助的。麻雀虽小五脏俱全。
其实就是利用一个工程对外放开服务,其他的服务都通过该服务进行跳转。
对于http://localhost:8888/hello/w 携带mycookie=mycookievalue 的cookie之后,转发到http://localhost:9999/hello/w。
spring:
cloud:
gateway:
routes:
- id: after_route #一个路由(服务)的唯一标识
uri: http://localhost:9999 #服务的地址
predicates: #过滤条件
- Cookie=mycookie,mycookievalue #必须cookie中携带mycookie=mycookievalue
server:
port: 8888