在 Spring3 中,如何在我的控制器中调用另一个服务器的控制器

In the Spring3,How to call a another server's controller in my controller

我有3台服务器,serverA,serverB,serverC,现在在serverC中,一些来自serverB的请求被处理,然后,我不知道结果是什么(响应),如果是resultA,我想把resultA作为请求给serverA,否则给serverB。

所以我可以在 serverC 的控制器中做些什么,或者设计中有问题。

请告诉我应该怎么做,谢谢。

这是我的代码。

服务器A

@RestController
public class ControllerA {

@RequestMapping(value = "/methodA", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<String> methodA(@RequestBody String something) {
    // some process
    return null;
}

服务器B

@RestController
public class ControllerB {

@RequestMapping(value = "/methodB", consumes =MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> methodB(@RequestBody String something) {
    // some process
    return null;
}

服务器C

@RestController
public class ControllerC {

public ResponseEntity<String> methodC(@RequestBody String someReq) {
    if (checkPam(someReq)) {
        **// I want to call the ControllerA in serverA.**
    }else {
        **// I want to call the ControllerB in serverB.**
    }
    return null;
}

您可以简单地使用 RestTemplate:

@RestController
public class ControllerC {

public ResponseEntity<String> methodC(@RequestBody String someReq) {
     RestTemplate restTemplate = new RestTemplate();
    if (checkPam(someReq)) {          
        String fooResourceUrl
           = "http://path-to-server-a/path-to-service-a";
        ResponseEntity<String> response
        = restTemplate.getForEntity(fooResourceUrl , String.class);
    }else {
        String fooResourceUrl
           = "http://path-to-server-b/path-to-service-b";
        ResponseEntity<String> response
        = restTemplate.getForEntity(fooResourceUrl , String.class);
    }
    return null;
}

如你所见,我通过 new 运算符实例化 RestTemplate 对象,你也可以在你的上下文中声明 RestTemplate bean,然后在你的控制器中自动装配它 class.