Spring boot2.0 入门(四)-使用RestTemplate 通信多个Spring boot工程

有时候项目中要建立多个微服务,或者把一个大的项目拆分成多个微服务进行解耦,为了方便完成各个微服务之间相互调用,
Spring给予了模板类RestTemplate,下面介绍一下RestTemplate的几种用法:
1.使用RestTemplate进行Get请求,请求参数较少

//通过用户ID获取用户信息
public User RestTemplateGet(Long id)
{
	RestTemplate restTemplate = new RestTemplate();
	User user = restTemplate.getForObject("http://localhost:8080/users/{id}", User.class, id);
	return user;
}

2.使用RestTemplate进行Get请求,请求参数多且可变

//通过用户的年龄,性别,所在城市获取用户列表
public List<User> RestTemplateGet(int age,int sex,String city)
{
	RestTemplate restTemplate = new RestTemplate();
	Map<String,Object> params = new HashMap<String,Object>();
	params.put("age",20);
	params.put("sex",1);
	params.put("city","南京");
	String url = "http://localhost:8080/users/{age}/{sex}/{city}";
	ResponseEntity<List> responseEntity = restTemplate.getForEntity(url, List.class,params);
	List<User> users = responseEntity.getBody();
	return users;
}

3.使用RestTemplate进行POST请求,请求参数在使用JSON请求体

//使用Post新增用户
public User RestTemplatePost(User user)
{
	HttpHeaders headers = new HttpHeaders();
	headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
	HttpEntity<User> request = new HttpEntity<>(user,headers);
	RestTemplate restTemplate = new RestTemplate();
	User user = restTemplate.postForObject("http://localhost:8080/users", request, User.class);
	return user;
}

4.使用RestTemplate进行DELETE请求,请求删除操作

//使用delete删除用户
public void RestTemplateDelete(Long id)
{
	RestTemplate restTemplate = new RestTemplate();
	restTemplate.delete("http://localhost:8080/users/{id}",id);
}

5.使用RestTemplate当成普通HTTP交互

//当成普通http请求
public void RestTemplateTest()
{
	HttpHeaders headers = new HttpHeaders();
	headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
	HashMap<String, String> maps = new HashMap<>();
	maps.put("method", "keepAlive");
	HttpEntity<Map> request = new HttpEntity<>(maps,headers);
	RestTemplate rest = new RestTemplate();
	String str = rest.postForObject("http://localhost:8080/Engine", request, String.class);
	System.out.println(str);
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值