1.网关的作用
-
路由转发
根据请求到网关的地址,将其转发到对应的服务上 -
过滤器
对请求进行统一的处理
2.搭建网关服务
2.1 引入gateway依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
2.2 配置(配置文件或者配置类)
配置文件:
spring:
application:
name: GATWAY
cloud:
consul:
host: localhost
port: 8500
gateway:
routes:
- id: test_order
uri: http://localhost:9991
predicates:
- Path=/order/**
- id: test_user
uri: http://localhost:9992
predicates:
- Path=/user/**
routes:路由集
id:路由id
uri:要转发的uri
predicates(表明、阐述、以什么为依据):大概意思就是路由的规则
Path:路径规则,路径为规定的请求就转发
配置类:
@Configuration
public class GatewayConfig{
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
return builder.routes()
.route("user_route", r -> r.path("/user")
.uri("http:localhost:8989"))
.route("order_route", r -> r.path("/order")
.uri("http:localhost:8999"))
.build();
}
}
链式编程,写多个路由。
推荐是使用配置文件的方式吧。
3.实现负载均衡
以上,我们的uri都是写死的。我们知道做微服务几乎都是集群的,这样写肯定是不行的。还记得Ribbon吗?能够实现负载均衡,它是根据服务名从服务注册中心拉取该服务名的所有节点到本地然后实现负载均衡。gateway的底层是有Ribbon的,所以我们可以像使用Ribbon那样在gatway中实现负载均衡,非常简单。
spring:
application:
name: GATWAY
cloud:
consul:
host: localhost
port: 8500
gateway:
routes:
- id: test_order
uri: ib://ORDER
predicates:
- Path=/order/**
- id: test_user
uri: http://localhost:9992
predicates:
- Path=/user/**
uri: http://localhost:9992 变为 uri: ib://ORDER 即可。lb意为loadbalance(负载均衡),根据ORDER从服务注册中心拉取名为ORDER的服务列表。
4.网关的Predicate和Filter
Predicate:
分为11中,上面我们用到的Path只是一种,比如After是在某个时间之后才能访问到uri的路径。Before就是某时间之前,Between就是之间,Cookie是请求中必须有这个cookie。。。。。就不一一举例了。可去官网细看
:https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/#gateway-request-predicates-factories
Filter:
Filter就更多了,有31种,这里截图部分
AddRequestHeader是给请求添加请求头,AddRequestParamter给请求添加参数。。。。。,细看可去官网