Spring Cloud Zuul 獲取當前請求的路由信息

基本思路

參考spring-cloud-zuul-ratelimit開源項目,在過濾器中根據當前的請求路徑,判斷當前的路由信息,當取得路由信息後,能夠對服務的調用次數作統計等操做。spring

具體實現

建立一個AbstractRouteFilter

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());
    }

}
相關文章
相關標籤/搜索