准备
服务端我是用的是一个普通的api
@restcontrollerpublic class servercontroller { @getmapping(/msg) public string msg(){ return this is product' msg; }}
第一种方式
直接使用resttemplate,url写死
@slf4j@restcontrollerpublic 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@restcontrollerpublic 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里使用应用名字)@componentpublic class resttemplateconfig { @bean @loadbalanced public resttemplate resttemplate(){ return new resttemplate(); }}
@slf4j@restcontrollerpublic 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; }}
以上就是resttemplate的三种用法介绍(代码)的详细内容。