什么是resttemplate
传统情况下在java代码里访问restful服务,一般 使用 apache的httpclient。不过此种方法使用起来太过繁琐。spring提供了一种简单便捷的模板类来进行操作,这就是resttemplate。
准备
服务端我是用的是一个普通的api
1 2 3 4 5 6 7 8 9 |
@restcontroller public class servercontroller {
@getmapping ( "/msg" ) public string msg(){ return "this is product' msg" ; }
} |
第一种方式
直接使用resttemplate,url写死
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
@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)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
@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里使用应用名字)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
@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
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
原文链接:https://segmentfault.com/a/1190000016796830
查看更多关于详解RestTemplate的三种使用方式的详细内容...