首先创建一个过滤器
package com.example.gatewaysample;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
@Component
@Slf4j
//GlobalFilter 全局filter GatewayFilter 局部filter
public class TimerFilter implements GatewayFilter, Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
StopWatch timer = new StopWatch();
timer.start(exchange.getRequest().getURI().getRawPath());
return chain.filter(exchange).then(
Mono.fromRunnable( ()-> {
timer.stop();
log.info(timer.prettyPrint());
}
)
);
}
@Override
public int getOrder() {
return 0;
}
}
配置过滤器
配置过滤器很简单: .filter(timerFilter)
package com.example.gatewaysample;
import org.springframework.beans.factory.annotation.Autowired;
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;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import java.time.ZonedDateTime;
@Configuration
public class GatewayConfiguration {
@Autowired
private TimerFilter timerFilter;
@Bean
@Order
public RouteLocator customizedRoutes(RouteLocatorBuilder routeLocatorBuilder){
return routeLocatorBuilder.routes()
.route(r->r.path("/java/**")
.and().method(HttpMethod.GET)
.and().header("name")
.filters(f->f.stripPrefix(1)
.addResponseHeader("java-param","gateway-config")
// .filter(timerFilter)
)
.uri("lb://feign-client")
)
.route(r->r.path("[表情]ckill/**")
.and().after(ZonedDateTime.now().plusMinutes(1))
.filters(f->f.stripPrefix(1))
.uri("lb://feign-client")
)
.build();
}
}
最后需要注意一点的是如果我们配置的是局部的过滤器就继承GatewayFilter,如果是全局就继承GlobalFilter,全局过滤器是不需要配置在路由规则中的,因为是全局,所以所有的路由都会首先进行全局过滤器的校验。