简体   繁体   中英

How to check the incoming request URL in rest api

I have a Rest API which takes json input from the user and makes connection (TCP connection) with the load balancer. One of the server behind the load balancer will process the request and sends back the response to the Rest API.

The Rest API accepts request from two different endpoints or URL's. Currently I have one load balancer which process the request from both the endpoints. I want to add one more load balancer.

Inside one of the method where I am making connection with the load balancer,I want to check the URL and redirect the request to particular load balancer depending upon the endpoint/URL.

Ex: URL1 request ---> redirect to load balancer 1.

URL2 request ----> redirect to load balancer 2.

You can redirect manually the request from client to specific LB based on requested path or you can use a api gateway like ZUUL .

Manually redirect exmaple:

@RequestMapping(value = { "/", " * " })
public ResponseEntity<?> redirectRequest(HttpServletRequest httpServletRequest) {
        String bodyRequest = "";
    String baseURL = "";
    if ("POST".equalsIgnoreCase(httpServletRequest.getMethod())
            || "PUT".equalsIgnoreCase(httpServletRequest.getMethod())) {
        try {
            bodyRequest = httpServletRequest.getReader().lines()
                    .collect(Collectors.joining(System.lineSeparator()));
        } catch (IOException e) {

        }
    }

    HttpEntity<?> request = new HttpEntity<>(bodyRequest);
    Enumeration<String> headerNames = httpServletRequest.getHeaderNames();

    if (headerNames != null) {
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            request.getHeaders().add(headerName, httpServletRequest.getHeader(headerName));
        }
    }

    if (httpServletRequest.getContextPath().contains("api/lb1"))
        baseURL = "lb ur1";
    else
        baseURL = "lb url 2";
    return restTemplate.exchange(baseURL + httpServletRequest.getContextPath(),
            HttpMethod.resolve(httpServletRequest.getMethod()), request, ResponseEntity.class,
            httpServletRequest.getRequestURI());

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM