链接
https://gitee.com/flowers-bloom-is-the-sea/rest-template-demo
服务2-moduleSecond
例子:
@CrossOrigin
@RestController
@RequestMapping("/hello")
public class HelloController {
@GetMapping("/get")
public String get(){
System.out.println("moduleSecond log........");
return "get ... moduleSecond_haha";
}
@PostMapping("/post")
public String post(@RequestBody Map<String,String> map){
System.out.println("moduleSecond map is "+map);
return "post ... moduleSecond_haha";
}
}
服务1-moduleOne
1、远程调用的配置:
@Configuration
public class RestTemplateConfiguration {
// @LoadBalanced
@Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setSupportedMediaTypes(Collections.singletonList(MediaType.TEXT_PLAIN));
restTemplate.getMessageConverters().add(converter);
return restTemplate;
}
}
2、案例
/**
* @author xin麒
* @date 2023/11/28 15:32
*/
@CrossOrigin
@RestController
@RequestMapping("/hello")
public class HelloController {
@GetMapping("/get")
public String get() {
System.out.println("moduleOne log........");
return "get ... moduleOne_haha";
}
@PostMapping("/post")
public String post(@RequestBody Map<String, String> map) {
System.out.println("moduleOne map is " + map);
return map.toString();
}
@Resource
private RestTemplate restTemplate;
private static final String otherServerUrl = "http://127.0.0.1:8082/xinqidev_moduleSecond/hello";
//http://127.0.0.1:8082/xinqidev_moduleSecond/hello/get
@GetMapping("/testOtherGetRest")
public String testOtherGetRest() {
String url = otherServerUrl + "/get";
System.out.println("url is " + url);
String object = restTemplate.getForObject(url, String.class);
System.out.println("object is " + object);
return object;
}
@PostMapping("/testOtherPostRest")
public String testOtherPostRest(@RequestBody Map<String, String> maps) {
Map<String, String> map = new HashMap<>();
map.put("1", "OtherPostRest_haha1");
map.put("2", "OtherPostRest_haha2");
String object = restTemplate.postForObject(otherServerUrl + "/post", map, String.class);
System.out.println("object is " + object);
return object;
}
private static final String mySelfUrl = "http://127.0.0.1:8081/xinqidev_moduleOne/hello";
@GetMapping("/testMySelfGetMethod")
public String testMySelfGetMethod() {
String object = restTemplate.getForObject(mySelfUrl + "/get", String.class);
System.out.println("object is " + object);
return object;
}
@PostMapping("/testMySelfPostMethod")
public String testMySelfPostMethod(@RequestBody Map<String, String> maps) {
Map<String, String> map = new HashMap<>();
map.put("1", "MySelfPostMethod_haha1");
map.put("2", "MySelfPostMethod_haha2");
String object = restTemplate.postForObject(mySelfUrl + "/post", map, String.class);
System.out.println("object is " + object);
return object;
}
}