RestTemplate API
实现服务间远程调用
一 postForObject
第一步在GoodsController里添加方法
@PostMapping("save")
public HashMap save(@RequestBody Goods goods) {
System.out.println(goods);
return new HashMap() {
{
put("code", 200);
put("msg", "goods save success");
}
};
}
第二步ordercontroller添加方法
@RequestMapping("test")
public String test() {
String serverName = "cloud-goods";
String url = "http://" + serverName + "/goods/save";
Goods goods = new Goods("华为",1);
HashMap hashMap = restTemplate.postForObject(url, goods, HashMap.class);
System.out.println(hashMap);
return "success";
}
结果访问:localhost:9002/order/test ,测试是否成功
二 ForEntity
postForEntity
@RequestMapping("/test1")
public String test1() {
String serverName = "cloud-goods";
String url = "http://" + serverName + "/goods/save";
Goods goods = new Goods("华为",1);
ResponseEntity<HashMap> result = restTemplate.postForEntity(url, goods, HashMap.class);
//拿结果数据的API(响应数据)
System.out.println(result.getBody());
//拿一些响应状态码
System.out.println(result.getStatusCode());
return "success";
}
结果访问:localhost:9002/order/test1
getForEntity
@RequestMapping("/test2")
public Map test2() {
//远程调用cloud-good服务,获取goods信息,发送http请求(httpclient)=> resttemplate
String serverName = "cloud-goods";
String url = "http://" + serverName + "/goods/findById/1";
ResponseEntity<Goods> result = restTemplate.getForEntity(url, Goods.class);
System.out.println(result.getBody());
System.out.println(result.getStatusCode());
//2.保存订单
System.out.println("保存成功");
return new HashMap() {
{
put("code", "200");
put("msg", "success");
}
};
}
结果访问:localhost:9002/order/test2