简体   繁体   中英

How to implement “load balancer” using spring boot?

Depends on request body content I need to redirect http requests to URL_1 or URL_2 .

I started controller implementation:

@RestController
public class RouteController {

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping(value = "/**")
    public HttpServletResponse route(HttpServletRequest request) {
        String body = IOUtils.toString(request.getReader());
        if(isFirstServer(body)) {
            //send request to URL_1 and get response
        } else {
            //send request to URL_2 and get response
        }
    }
}

Request might be GET or POST ot PUT or PATCH etc.

Could you help me to write that code?

I've asked a somehow similar question a while ago. Plea see Server side redirect for REST call for more context.

The best way (to my current understanding) you could achieve this is by manually invoking the desired endpoints from your initial endpoint.

@RestController
public class RouteController {

    @Value("${firstUrl}")
    private String firstUrl;

    @Value("${secondUrl}")
    private String secondUrl;

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping(value = "/**")
    public void route(HttpServletRequest request) {
        String body = IOUtils.toString(request.getReader());
        if(isFirstServer(body)) {
            restTemplate.exchange(firstUrl,
                                  getHttpMethod(request), 
                                  getHttpEntity(request), 
                                  getResponseClass(request), 
                                  getParams(params));
        } else {
            restTemplate.exchange(secondUrl,
                                  getHttpMethod(request), 
                                  getHttpEntity(request), 
                                  getResponseClass(request), 
                                  getParams(params))
        }
   }
}

Example implementation for getHttpMethod :

public HttpMethod getHttpMethod(HttpServletRequest request) {
    return HttpMethod.valueOf(request.getMethod());
}

Similar implementations for getHttpEntity , getResponseClass and getParams . They are used for converting the data from the HttpServletRequest request to the types required by the exchange method.

There seem to be a lot of better ways of doing this for a Spring MVC app, but I guess that it does not apply to your context.

Another way you could achieve this would be defining your own REST client and adding the routing logic there.

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