【SpringCloud】07. Communication between applications
•
Java
Inter application communication
HTTP vs RPC
1. Two restful invocation methods between services in spring cloud
Method 1: resttemplate: an HTTP client
There are three ways to resttemplate
1. Write URL directly: http://localhost:8080/msg
Use resttemplate getForObject(" http://localhost:8080/msg ", string. Class); method
@RestController
@Slf4j
public class ClientController {
@GetMapping("/getProductMsg")
public String getProductMsg(){
//1. 第一种方式
RestTemplate restTemplate = new RestTemplate();
String response = restTemplate.getForObject("http://localhost:8080/msg",String.class);
log.info("response={}",response);
return response;
}
}
Disadvantages: the address is dead. If the other party has more than one service, it's very bad.
2. Through serviceinstance, serviceinstance = loadbalancerclient choose("ServerId"); Get information about the service. Serverid: name of the service
@Autowired
private LoadBalancerClient loadBalancerClient;
@RestController
@Slf4j
public class ClientController {
@Autowired
private LoadBalancerClient loadBalancerClient;
@GetMapping("/getProductMsg")
public String getProductMsg(){
//2.第二种
ServiceInstance serviceInstance= loadBalancerClient.choose("PRODUCT");
String url = String.format("http://%s:%s",serviceInstance.getHost(),serviceInstance.getPort())+"/msg";
RestTemplate restTemplate = new RestTemplate();
String response = restTemplate.getForObject(url,response);
return response;
}
Advantages: we can not know the service path, but use the service ID or service path information. Disadvantages: the coding is cumbersome
3. Use @ loadbalanced to access the application name in resttemplate
@Component
public class RestTemplateConfig {
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
@RestController
@Slf4j
public class ClientController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/getProductMsg")
public String getProductMsg(){
//3.第三种方式 利用@LoadBalanced 可在restTemplate里使用应用名字
String response = restTemplate.getForObject("http://PRODUCT/msg",response);
return response;
}
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码