gateway
概念
springCloud网关组件
作用
鉴权、监控、限流、路由、负载均衡
使用步骤
1)导包
<!--Gateway(zuul)网关组件依赖包--><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-gateway</artifactId></dependency><!--Eureka Client依赖包,网关需要注册到注册中心--><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-eureka-client</artifactId></dependency>
2)配置
#网关核心要素:断言predicates-->过滤filter-->路由routeserver:port: 8001spring:application:name: gateway-web #网关工程名称,也就是ServiceIDcloud:gateway:globalcors:cors-configurations:'[/**]': # 匹配所有请求allowedOrigins: "*" #跨域处理 允许所有的域allowedMethods: # 支持的方法- GET- POST- PUT- DELETEroutes:- id: changgou-service-goods_route#lb表示loadbalanced,使用goods服务名从Eureka获取地址列表,通过负载均衡筛选一个服务器地址uri: lb://goodspredicates:- Path=/api/spu/**filters:#- PrefixPath=/brand- StripPrefix=1#用户微服务- id: changgou_user_routeuri: lb://userpredicates:- Path=/api/user/**filters:- StripPrefix=1
网关执行流程分析
#核心3要素:predicates:- Path=/api/spu/**filters:- StripPrefix=1uri: lb://goodshttp://localhost:8001/api/sku/index.htmlhttp://localhost:8001/api/spu/index.html1)判断请求路径“/api/sku/index.html”是否和断言的path="/api/spu/**"匹配断言“不匹配”--->不会被"过滤"和"路由"--->直接访问网关中的资源2)判断请求路径“/api/spu/index.html”是否和断言的path="/api/spu/**"匹配断言“匹配”--->会被"过滤"和"路由"过滤--->StripPrefix=1,去除请求路径中第一个“/”后的内容--->/spu/index.html路由--->lb://goods,从注册中心,负载均衡的获取一个服务器地址,拼接到”过滤后“的地址上,进行请求转发--->http://locahost:9001/spu/index.html注意:网关路由请求,默认使用的转发forward
3)代码
/*(1)在引导类添加@EnableEurekClient,把网关工程注入注册中心*/@SpringBootApplication@EnableEurekClientpublic class XxxGatewayApplication{}/*(2)定义全局或局部过滤器*//*(2.1)全局过滤器,特点:不需要配置,对所有路由生效;2个重要接口:GlobalFilter、Ordered*/@Componentpublic class XxxxFilter implements GlobalFilter, Ordered {/***exchange主要作用获取请求和响应对象 request、response*chain包含了所有的过滤器,在该对象中可以查看到所有要执行的过滤器,执行过滤器(增强)放行*/@Overridepublic Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {//业务增强return chain.filter(exchange);}@Overridepublic int getOrder() {return 0;//指定该全局过滤器在所有过滤器中的执行顺序,值越小优先级越高}}/*(2.2)局部过滤器,特点:需要配置,配置在那个路由对那个路由生效;1个重要接口:GatewayFilterFactory*//*特别注意:局部过滤器一定一定一定是以【GatewayFilterFactory】结尾,否则不生效*/@Componentpublic class XxxxGatewayFilterFactory implements GatewayFilterFactory{/*执行增强的业务逻辑*/@Overridepublic GatewayFilter apply(RequestCookieGatewayFilterFactory.Config config) {return (exchange, chain) -> {//业务增强return chain.filter(exchange);};}/*获取配置文件中过滤器传递过来的参数*/public class Config {private String params;public Config() {}public int getParams() {return this.params;}public void setParams(int params) {this.params = params;}}}
#局部过滤器配置文件#Xxxx代表局部过滤器的【类名称-GatewayFilterFactory】#【abc】就是传递给Config内部类的params参数值filters:- Xxxx=abc
