栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

详解RestTemplate的三种使用方式

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

详解RestTemplate的三种使用方式

 什么是RestTemplate

传统情况下在java代码里访问restful服务,一般使用Apache的HttpClient。不过此种方法使用起来太过繁琐。spring提供了一种简单便捷的模板类来进行操作,这就是RestTemplate。

准备

服务端我是用的是一个普通的API

@RestController
public class ServerController {

 @GetMapping("/msg")
 public String msg(){
  return "this is product' msg";
 }

}

第一种方式

直接使用restTemplate,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;
 }

}

第二种方式

第二种方式(利用loadBalancerClient通过应用名获取url,然后再使用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;
 }

}

第三种方式

第三种方式(利用@LoadBalanced,可再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;
 }

}

github项目

Cloud2Sell

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/139819.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号