[英]How to implement “load balancer” using spring boot?
根据请求正文的内容,我需要将http请求重定向到URL_1
或URL_2
。
我开始执行控制器:
@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
}
}
}
请求可能是GET
或POST
OT PUT
或PATCH
等。
您能帮我写那个代码吗?
我前段时间曾问过一个类似的问题。 请参阅服务器端重定向以进行REST调用以获得更多上下文。
(据我目前的理解),最好的方法是从初始端点手动调用所需的端点。
@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))
}
}
}
getHttpMethod
示例实现:
public HttpMethod getHttpMethod(HttpServletRequest request) {
return HttpMethod.valueOf(request.getMethod());
}
getHttpEntity
, getResponseClass
和getParams
类似实现。 它们用于将数据从HttpServletRequest request
转换为exchange
方法所需的类型。
对于Spring MVC应用程序似乎有很多更好的方法,但是我想这不适用于您的上下文。
您可以实现此目标的另一种方法是定义自己的REST客户端并在其中添加路由逻辑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.