參考spring-cloud-zuul-ratelimit開源項目,在過濾器中根據當前的請求路徑,判斷當前的路由信息,當取得路由信息後,能夠對服務的調用次數作統計等操做。spring
public abstract class AbstractRouteFilter extends ZuulFilter { private final RouteLocator routeLocator; private final UrlPathHelper urlPathHelper; AbstractRouteFilter(RouteLocator routeLocator,UrlPathHelper urlPathHelper){ this.routeLocator = routeLocator; this.urlPathHelper = urlPathHelper; } //核心邏輯,獲取請求路徑,利用RouteLocator返回路由信息 protected Route route(HttpServletRequest request){ String requestURI = urlPathHelper.getPathWithinApplication(request); return routeLocator.getMatchingRoute(requestURI); } }
使用時,繼承AbstractRouteFilter便可,下面演示一個服務調用次數的過濾器示例ide
public class RouteTimesFilter extends AbstractRouteFilter { public RouteTimesFilter(RouteLocator routeLocator, UrlPathHelper urlPathHelper) { super(routeLocator,urlPathHelper); } @Override public String filterType() { //能夠根據業務要求,修改過濾器類型 return "post"; } @Override public int filterOrder() { //過濾器順序 return 0; } @Override public boolean shouldFilter() { //能夠根據業務要求,過濾相關路由 return true; } @Override public Object run() { RequestContext ctx = RequestContext.getCurrentContext(); Route route = route(ctx.getRequest()); //獲取到路由信息,就能夠作想要作的事了 System.out.println(route); return null; } }
@Component public class ZuulFilterConfig { @Bean public ZuulFilter routeTimesFilter(RouteLocator routeLocator){ return new RouteTimesFilter(routeLocator,new UrlPathHelper()); } }