介绍
通过Gateway可以统一的为所有微服务进行鉴权、日志、限流等操作。在没gateway类似的框架之前,你需要在每个微服务里放安全、日志、限流的代码。
Route(路由)
由一个 ID,一个目标 URI,一组断言和一组过滤器定义。如果Predicate(断言)为真,则路由匹配,匹配举例:/info 。
Predicate(断言)
用它来匹配来自 HTTP 请求的任何内容,例如 headers 或参数。
Filter(过滤器)
用它修改请求和响应。
uri
断言匹配后,跳转哪个URI,例:http://httpbin.org:80
以lb://开头的(lb代表从注册中心获取服务),后面接的就是你需要转发到的服务名称,这个服务名称必须跟eureka中的对应,否则会NotFoundException: Unable to find instance for xxx
yml配置
匹配host为aa.org或bb.org,路径为/red/anything,将响应的头信息里添加X-Response-Red,值为Blue。
spring:
cloud:
gateway:
routes:
- id: path_route
uri: https://example.org
predicates:
- Path=/red/*
- Host=**.aa.org,**.bb.org
filters:
- AddResponseHeader=X-Response-Red, Blue
代码配置
处理同上面的yml一样,还可以配置根据时间、请求的方法、头信息等等做处理。
@Bean
public RouteLocator myRoutes(RouteLocatorBuilder builder) {
return builder.routes()
.route(p -> p
.host("*.aa.org","*.bb.org")
.and()
.path("/red/*")
.filters(f -> f
.addResponseHeader("X-Response-Red","blue"))
.uri("http://httpbin.org:80")).
build();
}