java resttemplate_详解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项目

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

希望与广大网友互动??

点此进行留言吧!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值