RPC(Remote Produce Call) 远程过程调用:
1,基于socket
2,自定义数据格式
3,速度快,效率高
4,典型应用代表:Dubbo,WebSocket,ElasticSearch集群间相互调用
HTTP网络传输协议:
1,基于TCP/IP协议
2,规定数据传输格式
3,缺点:消息封装比较臃肿,传输速度较慢
4,优点是对服务提供和调用方式没有任何技术限定,自由灵活,比较符合微服务概念。
简单使用RestTemplate
服务1
@SpringBootApplication
public class ConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class,args);
}
@Bean
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
@RestController
@RequestMapping("cuser")
public class ComsumerUserController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/{id}")
public User cuser(@PathVariable("id") Integer id) throws URISyntaxException {
//模拟浏览器发送请求
User forObject = restTemplate.getForObject("http://127.0.0.1:8080/user/"+id, User.class);
return forObject;
}
}
post请求
@PostMapping
public String saveUser(@RequestBody User user){
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/json;charset=UTF-8");
HttpEntity<User> request = new HttpEntity<>(user, headers);
ResponseEntity<String> integerResponseEntity = restTemplate.postForEntity("http://127.0.0.1:18081/user", request, String.class);
String id = integerResponseEntity.getBody();
return "添加成功id:"+id;
}
服务2
@RestController
@RequestMapping("user")
public class UserController {
@GetMapping("/{id}")
public User findById(@PathVariable("id") Integer id){
User user = new User();
user.setId(id);
user.setName("张"+id);
user.setAge(18);
return user;
}
}