Route (路由): 路由是构建网关的基本模块,它由 ID,目标 URI,一系列的断言和过滤器组成,如果断言为true则匹配该路由
Predicate(断言):参考的是 java8 的 java.util.function.Predicate 开发人员可以匹配 HTTP 请求中的所有内容(例如请求头或请求参数),如果请求与断言相匹配则进行路由
Filter(过滤):指的是 Spring 框架中 GatewayFilter 的实例,使用过滤器,可以在请求被路由前或者之后对请求进行修改
pom文件
<?xml version="1.0" encoding="UTF-8"?>
yml文件
server: port: 9527spring: application: name: cloud-gateway-gateway9527 cloud: gateway: routes: - id: payment8001 uri: lb://SPRING-CLOUD-PAYMENT predicates: - Path=/payment/selectById/**eureka: instance: instance-id: cloud-gateway-gateway9527 client: #表示是否将自己注册进EurekaServer,默认为true register-with-eureka: true # 是否从EurekaServer抓取已有的注册信息,默认为毛白前,单节点无所谓,集群必须设置为true,才能配合ribbon使用负载均衡 fetch-registry: true service-url: defaultZone: http://localhost:7001/eureka,http://localhost:7002/eureka
主启动类
package com.xx.job.cloudgatewaygateway9527;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.client.discovery.EnableDiscoveryClient;import org.springframework.cloud.netflix.eureka.EnableEurekaClient;@EnableEurekaClient@SpringBootApplication@EnableDiscoveryClientpublic class CloudGatewayGateway9527Application { public static void main(String[] args) { SpringApplication.run(CloudGatewayGateway9527Application.class, args); }}
gateway的两种配置方式
方式一:上面的yml配置方式
方式二:java类配置
package com.xx.job.cloudgatewaygateway9527.config;import org.springframework.cloud.gateway.route.RouteLocator;import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;@Configurationpublic class GatewayConfig { @Bean public RouteLocator routeLocator(RouteLocatorBuilder routeLocatorBuilder){ RouteLocatorBuilder.Builder routes = routeLocatorBuilder.routes(); RouteLocator build = routes.route("payment8001", r -> r.path("/payment/selectById/**").uri("lb://SPRING-CLOUD-PAYMENT")) // .route("payment8002", r -> r.path("/payment/get/**").uri("http://127.0.0.1:8002")) .build(); return build; }}
git:spring-cloud-demo: spring-cloud-demo试例