Spring cloud gateway是spring官方基于Spring 5.0、Spring Boot2.0和Project Reactor等技术开发的网关,Spring Cloud Gateway旨在为微服务架构提供简单、有效和统一的API路由管理方式,Spring Cloud Gateway作为Spring Cloud生态系统中的网关,目标是替代Netflix Zuul,其不仅提供统一的路由方式,并且还基于Filer链的方式提供了网关基本的功能,例如:安全、监控/埋点、限流等
如图:gateway网关流程图如下
2.SpringBoot配置GateWay网关 (1)pom.xml文件:
(2)application.yml文件: org.springframework.cloud spring-cloud-starter-gatewaycom.alibaba.cloud spring-cloud-starter-alibaba-nacos-discovery
# 服务端口
server:
port: 80
spring:
application:
name: service-gateway # 服务名
# nacos服务地址
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
gateway:
discovery:
locator:
enabled: true #开启从注册中心动态创建路由的功能,利用微服务名进行路由
#设置路由id
routes:
- id: service1 #路由的ID,没有固定规则,但要求唯一,建议配合服务名
uri: lb://service1 #匹配后提供服务的路由地址
predicates:
- Path=service2
@SpringBootApplication
@EnableDiscoveryClient //开启nacos服务注册
public class GateWayMainApplication {
public static void main(String[] args) {
SpringApplication.run(GateWayMainApplication.class,args);
}
}
(4)编写配置类:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlbasedCorsConfigurationSource;
import org.springframework.web.util.pattern.PathPatternParser;
@Configuration
public class CorsConfig {
@Bean
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);
}
}
(5)测试网关:
如图:测试入口改成 ==> http://localhost/



