传统情况下在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项目
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。
如对本文有疑问, 点击进行留言回复!!
SpringBoot实现本地存储文件上传及提供HTTP访问服务的方法
Java实现AES/CBC/PKCS7Padding加解密的方法
SpringBoot整合Spring Security的详细教程
IDEA 非常重要的一些设置项(一连串的问题差点让我重新用回 Eclipse)
详解Springboot2.3集成Spring security 框架(原生集成)
网友评论