gateway:
- 导入依赖
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Hoxton.SR3</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2.2.1.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
</dependencies>
- 配yml
server:
port: 8989
spring:
application:
name: gateway
cloud:
nacos:
discovery:
server-addr: localhost:8848
config:
server-addr: localhost:8848
file-extension: yaml
gateway:
discovery:
locator:
enabled: true # 开启微服务名字转发
routes:
- id: payment
uri: lb://provider-payment
predicates:
- Path=/payment/**
# filters:
# - name: RequestRateLimiter
# args:
# redis-rate-limiter.replenishRate: 1
# redis-rate-limiter.burstCapacity: 2
# key-resolver: "#{@ipKeyResolver}"
- id: consumer
uri: lb://consumer-order
predicates:
- Path=/order/**
filters:
- StripPrefix=1 # 截取一段前缀
Noting:filters 和 predicates 都有s ,少写会失败
-
启动类上加上注册与发现:@EnableDiscoveryClient
-
全局filter。因为使用的是Webflux,所以用exchange替代了request和respond。chain代表链条,来回都会经过。order 表示优先级,数字越小优先级越高。返回
Mono<Void>
等同于void,无实际含义。
@Configuration
@Slf4j
public class ParamConfiguration implements GlobalFilter, Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
log.info("custom global filter");
System.out.println("exchange.getRequest().getPath() = " + exchange.getRequest().getPath());
return chain.filter(exchange);
}
@Override
public int getOrder() {
return 0;
}
}