6、spring-cloud-gateway
依赖
<dependencies><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-gateway</artifactId></dependency><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-loadbalancer</artifactId></dependency></dependencies>
配置文件
server:port: 8080spring:application:name: gatewaycloud:nacos:discovery:server-addr: localhost:8848gateway:routes:- id: ms1uri: lb://ms1predicates:- Path=/ms1/**filters:- RewritePath=/ms1/?(?<segment>.*),/$\{segment}- id: ms2uri: lb://ms2predicates:- Path=/ms2/**filters:- RewritePath=/ms2/?(?<segment>.*),/$\{segment}- id: ms3uri: lb://ms3predicates:- Path=/ms3/**filters:- RewritePath=/ms3/?(?<segment>.*),/$\{segment}
配置类
可自定义断言工厂、拦截器工厂、全局拦截器
自定义全局拦截器
@Slf4j
@Component
public class MyGlobalFilter implements GlobalFilter, Ordered {@Overridepublic Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {ServerHttpRequest request = exchange.getRequest();ServerHttpResponse response = exchange.getResponse();String uri = request.getURI().toString();StopWatch stopWatch = new StopWatch();stopWatch.start();log.info("请求【{}】开始,时间:{}", uri, LocalDateTime.now());// 放行Mono<Void> mono = chain.filter(exchange).doFinally((result) -> {stopWatch.stop();log.info("请求【{}】结束,时间:{},耗时:{}s", uri, LocalDateTime.now(), stopWatch.getTotalTimeSeconds());});return mono;}@Overridepublic int getOrder() {// 数字越小,优先级越高return 0;}
}