提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
前言
提示::
官方开发文档地址
https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/
提示:
一、gateway搭建
1. pom
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
2. yaml
1 注册
要使用gateway,先注入到服务注册中心中,以alibaba下的开源nacos为例
spring:
application:
name: gulimall-gateway
cloud:
nacos:
discovery:
server-addr: localhost:8848
2 配置路由与路径重写
再去配置gateway相关yaml,这里以配置路由(routes)和路径重写(RewritePath)
spring:
application:
name: gulimall-gateway
cloud:
nacos:
discovery:
server-addr: localhost:8848
gateway:
routes:
#==========================以api开头的都是前端发请求==============
- id: product_route #处理商品服务,精确路由
uri: lb://gulimall-product
predicates:
- Path=/api/product/**
filters:
- RewritePath=/api/?(?<segment>.*), /$\{segment}
#===========================模糊路由=============================
- id: renren_fast
uri: lb://renren-fast
predicates:
- Path=/api/**
filters:
- RewritePath=/api/?(?<segment>.*), /renren-fast/$\{segment}
server:
port: 88
3.主启动类
@EnableDiscoveryClient
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
public class GulimallGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GulimallGatewayApplication.class, args);
}
}
二、网关统一配置跨域
1. 问题分析:
浏览器不能执行其他网站的脚本,是由浏览器的同源策略造成的,是浏览器对javascript施加的安全限制
同源策略:是指协议,域名,端口要相同,任何一个不一样都会产生跨域问题
2.预检请求
发起方发送一个预检请求Request Method: OPTIONS
给服务器,获知服务器是否允许该实际请求,可以以这个原理解决跨域问题
3.解决跨域有2种办法
1 通过nginx反向代理服务器
通过nginx代理服务器,暴露一个相同的端口给浏览器,解决了跨域问题,但是如果开发的项目庞大,且每次需要去部署服务器里对nginx做nginx.conf配置,不方便解耦。
2 通过网关配置CorsWebFilter之后,不要加@CrossOrigin
代码
@Configuration
public class GuliMallCorsConfiguration {
@Bean
public CorsWebFilter corsWebFilter(){
//配置跨域
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.setAllowCredentials(true); //允许携带cookie
UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
urlBasedCorsConfigurationSource.registerCorsConfiguration("/**",corsConfiguration);
return new CorsWebFilter(urlBasedCorsConfigurationSource);
}
}