This article brings you an introduction to the three ways to use RestTemplate (code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Preparation
I am using a common API on the server side
@RestController public class ServerController { @GetMapping("/msg") public String msg(){ return "this is product' msg"; } }
The first way
Use restTemplate directly and write the url
@Slf4j @RestController public class ClientController { @GetMapping("/getProductMsg") public String getProductMsg(){ // 1、第一种方式(直接使用restTemplate,url写死) RestTemplate restTemplate = new RestTemplate(); String response = restTemplate.getForObject("http://localhost:9082/msg",String.class); log.info("response={}",response); return response; } }
The second way (use loadBalancerClient to get the url through the application name, and then use restTemplate)
@Slf4j @RestController public class ClientController { @Autowired private LoadBalancerClient loadBalancerClient; @GetMapping("/getProductMsg") public String getProductMsg(){ //2、第二种方式(利用loadBalancerClient通过应用名获取url,然后再使用restTemplate) 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,String.class); log.info("response={}",response); return response; } }
The third method (using @LoadBalanced, you can use the application name in restTemplate)
@Component public class RestTemplateConfig { @Bean @LoadBalanced public RestTemplate restTemplate(){ return new RestTemplate(); } }
@Slf4j @RestController public class ClientController { @Autowired private RestTemplate restTemplate; @GetMapping("/getProductMsg") public String getProductMsg(){ //3、第三种方式(利用@LoadBalanced,可再restTemplate里使用应用名字) String response = restTemplate.getForObject("http://PRODUCT/msg",String.class); log.info("response={}",response); return response; } }
The above is the detailed content of Introduction to three usages of RestTemplate (code). For more information, please follow other related articles on the PHP Chinese website!