RestTemplate的简单使用
RestTemplate的简单使用
RestTemplate是httpclient的封装,提供了多种便捷访问远程Http服务的方法,是一种简单便捷的访问restful服务模板类,是Spring提供的用于访问Rest服务的客户端模板工具集,类似于jdbcTemplate、redisTemplate
使用restTemplate访问restful接口很简单:
(url,requestMap,ResponseBean.class)这三个参数分别代表rest请求地址、请求参数、htt响应被转换成的对象类型
案例:
编写配置类,将RestTemplate对象放入spring容器
package com.yl.order.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
/**
* RestTemplate配置类
*
* @auther Y-wee
*/
@Configuration
public class ApplicationContextConfig {
@Bean
// 开启默认负载均衡
@LoadBalanced
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
}
在controller中使用RestTemplate调用远程服务
package com.yl.order.controller;
import com.yl.common.entity.CommonResult;
import com.yl.common.entity.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
/**
* 订单
*
* @auther Y-wee
*/
@RequestMapping("/order")
@RestController
@Slf4j
public class OrderController {
@Resource
private RestTemplate restTemplate;
// 被调用服务的URL
// public static final String PAYMENT_URL = "http://localhost:8001";
/**
* 当被调用的服务注册了多个服务实例时,通过注册的服务名来调用,URL不能写死,
* 同时RestTemplate需要开启负载均衡告诉客户端调用哪个端口的服务
*/
public static final String PAYMENT_URL = "http://PAYMENT";
/**
* 添加数据
*
* @param payment payment
* @return 添加结果
*/
@GetMapping("/postForObject/payment/create")
public CommonResult<Payment> postForObject(Payment payment) {
// 发送post请求,返回对象为响应体中数据转化成的对象,基本上可以理解为json
// return restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, CommonResult.class);
return restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, CommonResult.class);
}
/**
* 添加数据
*
* @param payment payment
* @return 添加结果
*/
@GetMapping("/postForEntity/payment/create")
public CommonResult<Payment> postForEntity(Payment payment) {
// 发送post请求,返回对象为ResponseEntity,包含了响应中的一些重要信息,比如响应头、响应状态码、响应体等
ResponseEntity<CommonResult> entity = restTemplate.postForEntity(PAYMENT_URL + "/payment/create", payment, CommonResult.class);
if (entity.getStatusCode().is2xxSuccessful()) {
return entity.getBody();
} else {
return new CommonResult<>(444, "操作失败");
}
}
/**
* 查询数据
*
* @param id id
* @return 查询结果
*/
@GetMapping("/getForObject/payment/get/{id}")
public CommonResult<Payment> getForObject(@PathVariable("id") Long id) {
// 发送get请求
return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
}
/**
* 查询数据
*
* @param id id
* @return 查询结果
*/
@GetMapping("/getForEntity/payment/get/{id}")
public CommonResult<Payment> getForEntity(@PathVariable("id") Long id) {
// 发送get请求
ResponseEntity<CommonResult> entity = restTemplate.getForEntity(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
if (entity.getStatusCode().is2xxSuccessful()) {
return entity.getBody();
} else {
return new CommonResult<>(444, "操作失败");
}
}
}
被调用服务的controller
package com.yl.payment.controller;
import com.yl.common.entity.CommonResult;
import com.yl.common.entity.Payment;
import com.yl.payment.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
/**
* 支付
*
* @auther Y-wee
*/
@RestController
@Slf4j
@RequestMapping("/payment")
public class PaymentController {
@Resource
private PaymentService paymentService;
@Value("${server.port}")
private String serverPort;
/**
* 添加数据
*
* @param payment payment
* @return 添加结果
*/
@PostMapping(value = "/create")
public CommonResult create(@RequestBody Payment payment) {
int result = paymentService.create(payment);
if (result > 0) {
return new CommonResult(200, "插入数据库成功:"+serverPort, result);
}
return new CommonResult(444, "插入数据库失败", null);
}
/**
* 查询数据
*
* @param id id
* @return 查询结果
*/
@GetMapping(value = "/get/{id}")
public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id) {
Payment payment = paymentService.getPaymentById(id);
if (payment != null) {
return new CommonResult(200, "查询成功:"+serverPort, payment);
}
return new CommonResult(444, "没有对应记录,查询ID: " + id, null);
}
}
记得快乐
分类:
SpringCloud
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
2021-03-12 Docker 网络