流程
请求到达网关(将请求发给网关http://localhost:88/xxx),网关先根据判断请求符合哪个断言(Prediccate),再将请求路由给该断言所在的route,要到指定地方还要经一系列Filter进行处理
创建、测试网关
- 使用springboot向导新建网关模块,创建时勾选gateway,引入nacos依赖(gateway模块需要添加到注册中心)
- 把网关添加到注册中心,注册到注册中心可参考=>SpringCloud Alibaba-Nacos作为注册中心
- application.yml
server: port: 88 spring: application: name: gateway cloud: nacos: discovery: server-addr: 127.0.0.1:8848 gateway: routes: - id: test_route uri: http://www.baidu.com predicates: - Query=url,baidu
-
启动网关,访问http://localhost:88/?url=baidu即可看到效果
配置网关路由与路径重写
浏览器请求访问88端口,即访问路由,路由再将请求转发至对应的服务
例子:
前端请求:http://localhost:88/api/captcha.jpg?uuid=482769ee-5601-44a0-8de4-3c76df90631c
实际想要访问的地址:http://localhost:8080/renren-fast/captcha.jpg?uuid=482769ee-5601-44a0-8de4-3c76df90631c
可以发现,请求与实际要访问的地址不同的是
1)端口号
2)/api换成/renren-fast,也就是路径由/api重写成了/renren-fast
请求88端口,请求来到网关,网关判断请求符合哪个断言规则,比如上面请求符合“以/api开头”这个断言规则,根据配置文件,网关将其转给renren-fast,如果不写过滤器的话,请求来到http://renrenfast:renrenfast端口/captcha.jpg?uuid=482769ee-5601-44a0-8de4-3c76df90631c
网关路由规则参考Spring Cloud Gateway官网
路径重写参考Spring Cloud Gateway官网
spring:
cloud:
gateway:
routes:
- id: admin_route
uri: lb://renren-fast
predicates:
- Path=/api/**
filters:
- RewritePath=/api/(?<segment>/?.*), /renren-fast/$\{segment}
网关统一配置跨域
config包下CorsConfiguration类,复制粘贴以下代码即可,其他地方如果有对跨域的相关处理需要注释掉其他地方的处理
@Configuration
public class CorsConfiguration {
@Bean
public CorsWebFilter corsWebFilter(){
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
org.springframework.web.cors.CorsConfiguration corsConfiguration = new org.springframework.web.cors.CorsConfiguration();
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.setAllowCredentials(true);
source.registerCorsConfiguration("/**",corsConfiguration);
return new CorsWebFilter(source);
}
}