创建网关微服务
添加依赖
修改 gateway 服务的 pom.xml
<dependencies>
<dependency>
<groupId>top.it6666</groupId>
<artifactId>common_utils</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!--gson-->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
<!--服务调用-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
</dependencies>
创建 gateway 启动类
/**
* @author BNTang
*/
public class GateWayApplication {
public static void main(String[] args) {
SpringApplication.run(GateWayApplication.class, args);
}
}
在 resources 当中创建配置文件 application.yml
logging
pattern
console"%d{HH:mm:ss.SSS} %clr(%5p) %clr(-){faint} %clr(%-80.80logger{79}){cyan} %clr(:) %m%n"
server
port9000
spring
application
# 此实例注册到服务端的name
name gateway
cloud
nacos
discovery
server-addr localhost8848
gateway
discovery
locator
enabledtrue
routes
id service-video
uri lb //service-video
predicates
Path=/service_video/**
id service-vod
uri lb //service-vod
predicates
Path=/service_vod/**
id service-upload
uri lb //service-upload
predicates
Path=/service_upload/**
在 gateway 当中添加跨域配置处理如下, 创建 config 包, 在该包下创建跨域处理配置
/**
* @author BNTang
*/
public class CorsConfig {
public CorsWebFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.addAllowedMethod("*");
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
source.registerCorsConfiguration("/**", config);
return new CorsWebFilter(source);
}
}
取消控制器上的跨域注解, 把前端请求地址改成网关请求地址如下图,Controller 跨域注解全部去除
修改前端为 gateway 请求地址