当前位置: 移动技术网 > IT编程>开发语言>Java > 详解RestTemplate的三种使用方式

详解RestTemplate的三种使用方式

2019年07月19日  | 移动技术网IT编程  | 我要评论

什么是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

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网