Use ZuulFilter forward routing

Background: The reconstruction project, the production line url needs to be forwarded through the gateway to a different service as required, previously used custom route, the route configuration file yml forward way to do it, have a problem that is zuul.route <self. define a serviceid> .path = / account / ** zuul.route. <customize a serviceid> .serviceId = account, but can not guarantee the request url, consistent path / account / url path behind the service account with the inside, so this will be a problem. In this case, only in another way, and that is forwarded through the filter

1. Gateway Code

@Component
public class CommonServicePathFilter extends ZuulFilter {

    private final static String GETWAY_FOWARD_PREFIX="getway_forward_";

    private final static String GETWAY_COMPAY_CONFIG_KEY = "getway_company";

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public String filterType() {
       //这里很重要,必须是route
        return "route";
    }

    @Override
    public int filterOrder() {
        return 1;
    }


    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        String url = ctx.getRequest().getRequestURI();
        Map<String,String> forwardMap =  getForwardMap(url);
        if(forwardMap != null){
            String fowardUrl = forwardMap.get(url);
            String serviceId = getServiceId(fowardUrl);
            String requestUrl = getRequestUrl(fowardUrl,serviceId);
              //1.设置目标service的Controller的路径
            ctx.put(FilterConstants.REQUEST_URI_KEY,requestUrl);
             //2.设置目标service的serviceId
            ctx.put(FilterConstants.SERVICE_ID_KEY,serviceId);
        }
        return null;
    }
    private String getServiceId(String url){
        if(url.startsWith("/")){
            String temp = url.substring(1);
            return temp.split("/")[0];
        }else{
            return null;
        }
    }

    privateGetRequestUrl String (String URL, the serviceId String) {
         return url.substring (serviceId.length () + 1'd ); 
    } 

    @Override 
    public  Boolean shouldFilter () {
        return  to true ; 
    } 



    Private the Map <String, String> getForwardMap (originalUrl The String) {
            // TODO: here is to return a map, pass a originUrl, a return to forward url 
    } 

}

 

2. Pit

 A lot of information online say needs to be done

ctx.put (FilterConstants.REQUEST_URI_KEY, requestUrl); 
but after I use, has been reported to 404, then tracking service, found that in fact there is also a ctx serviceId the property, which is kept with the original url mapping serviceId current request the same, but if you want to forward serviceId not this, then it will report 404, it is necessary to redefine serviceId here,
 ctx.put(FilterConstants.SERVICE_ID_KEY,serviceId);

Guess you like

Origin www.cnblogs.com/logan-w/p/12498943.html