在学习本章之前,请先看《Spring Cloud Config 配置中心使用(技术篇)》
1.gateway是什么:
gateway是在spring生态系统之上构建的API网关服务,基于Spring 5,Spring Boot2和Project Reactor等技术。gateway旨在提供一种简单而有效的方式来对API进行路由,以及提供一些强大的过滤器功能,例如:反向代理、熔断、限流、重试等
2.gateway的特性
- 动态路由,能够匹配任何请求属性;
- 可以对路由指定Predicate(断言)和Filter(过滤器),且易于编写;
- 集成Hystrix的断路器功能;
- 集成SpringCloud服务发现功能;
- 请求限流功能;
- 支持路径重写。
3.三大核心概念
1.Route(路由):路由是构建网关的基本模块,它有ID,目标URI,一系列的断言和过滤器组成,如果请求与断言相匹配则进行路由
2.Predicate(断言):参考的是java8的java.util.function.Predicate,开发人员可以匹配HTTP请求中的所有内容(例如请求头或请求参数),如果请求与断言相匹配则进行路由
3.Filter(过滤):指的是Spring框架中GatewayFilter的实例,使用过滤器,可以在请求被路由前或者之后对请求进行修改。
4.总结
客户端向Spring Cloud Gateway发出请求。如果网关处理程序映射确定请求与路由匹配,则将其发送到网关Web处理程序。该处理程序通过特定于请求的过滤器链运行请求。筛选器由虚线分隔的原因是,筛选器可以在发送代理请求之前和之后运行逻辑。所有“前置”过滤器逻辑均被执行。然后发出代理请求。发出代理请求后,将运行“后”过滤器逻辑。
1.先创建模块在pom中加入如下依赖:(版本有springboot控制)
<!-- gateway网关核心依赖--> <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>
2.编写配置文件:
#服务的端口号 server: port: 88 #服务的名称 spring: application: name: gulimall-gateway #nacos注册中心地址 cloud: nacos: discovery: server-addr: 127.0.0.1:8848 #配置gateway网关实现路由转发 gateway: routes: # 设置路由id:id是名字表示 - id: admin_route #-lb是负载均衡,后面是服务名 #设置路由的uri,这个是远程服务的名字 #uri表示转到哪个远程服务进行处理 uri: lb://renren-fast #指定路由断言, 这个是路径中的匹配所有请求中带有这个路径的都会被这个网关处理 predicates: - Path=/api/** # - 重写路径,把api换成远端服务注册中心中的服务端口,并把api后面的东西都放在服务的后面进行调用 # 所有拦截的请求都会先进行路径的重写,再由uri转到对应的远程服务进行处理 filters: - RewritePath=/api/(?<segment>.*),/renren-fast/$\{segment}
3.配置跨域过滤器
@Configuration public class GulimallCorsConfiguration { @Bean public CorsWebFilter getCorsWebFilter(){ UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource(); CorsConfiguration corsConfiguration = new CorsConfiguration(); //配置跨域 corsConfiguration.addAllowedHeader("*"); corsConfiguration.addAllowedMethod("*"); corsConfiguration.addAllowedOrigin("*"); corsConfiguration.setAllowCredentials(true); urlBasedCorsConfigurationSource.registerCorsConfiguration("/**",corsConfiguration); return new CorsWebFilter(urlBasedCorsConfigurationSource); } }
4.编写主启动类(需要服务注册)
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class) @ComponentScan(basePackages = {"com.atguigu"}) @EnableDiscoveryClient//服务注册 public class ApiGatewayApplication { public static void main(String[] args) { SpringApplication.run(ApiGatewayApplication.class,args); } }