答案 0 :(得分:2)
在两个微服务上创建一个类,或者创建该类的jar并添加到两个微服务中,以便它们都可以访问相同的数据。
让我们说课程是
class TestData{
private String name;
private String id;
// getters and setters
}
现在您可以将数据从M1发送到M2,如下所示
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
TestData data = new TestData();
HttpEntity<?> entity = new HttpEntity<Object>(data,headers);
ResponseEntity<Object> responseEntity = restTemplate.exchange("url", HttpMethod.POST, entity, Object.class);
在Microservice M2中,您可以编写一个控制器来获取数据并按如下方式处理
@RequestMapping(value="/url",method=RequestMethod.POST)
public Object do(@RequestBody TestData data){
// do something
return //something
}
答案 1 :(得分:0)
假设您有MicroService1,该MicroService1需要将JSONObject => JsonObject发送到另一台MicroService2,该MicroService2位于不同计算机上但在同一网络上。
发送方:
RestTemplate restTemplate = new RestTemplate();
String jsonString = restTemplate.postForObject("http://10.177.7.128:8080/user/insertJsonObject",jsonObject,String.class);
restTemplate.postForObject的语法为:
ResponseType var1 = restTemplate.postForObject("network ip Address:portnumber/path",JSONObject,ResponseType)
要了解URI,请转到系统偏好设置>网络
要在接收方接收对象
@RequestMapping(value="/user/insertJsonObject", method=RequestMethod.POST)
public String updateProductSold(@RequestBody JSONObject jsonObject) {
...Body
...
...
return responseStatus;
答案 2 :(得分:-1)
以下是示例代码
public class Test {
public static void main(String[] args) {
String jsonString = "{\"id\" : \"123\",\"name\" : \"Tom\",\"class\" : {\"subject\" : \"Math\",\"teacher\" : \"Jack\"}}";
RestTemplate restTemplate = new RestTemplate();
String url = "http://192.1168.1.190:8080/test" // url for second service
System.out.println(responserEntityValue(jsonString,restTemplate,url,HttpMethod.POST,String.class));
}
public ResponseEntity<String> responserEntityValue(final String body, final RestTemplate restTemplate,
final String uRL, final HttpMethod requestMethod, final Class<String> stringClass) {
HttpHeaders headers = new HttpHeaders();
// Set all headers
headers.add(DatabaseConstants.CONTENT_TYPE, "application/json");
HttpEntity<String> request = new HttpEntity<>(body, headers);
return restTemplate.exchange(uRL, requestMethod, request, stringClass);
}