文章目录
Spring boot restTemplate
上一节 spring boot 数据库连接池
源码
Spring boot restTemplate
简介
restTemplate 是spring 提供的进行http 访问的工具;spring boot 中已经配置好了;
springboot 中 对 restTemplate 的支持
在 RestTemplateAutoConfiguration 中可以看到 已经创建了 bean, RestTemplateBuilder (注意springboot版本,我的为2.1.6)
@Bean
@ConditionalOnMissingBean
public RestTemplateBuilder restTemplateBuilder() {
RestTemplateBuilder builder = new RestTemplateBuilder();
HttpMessageConverters converters = this.messageConverters.getIfUnique();
if (converters != null) {
builder = builder.messageConverters(converters.getConverters());
}
List<RestTemplateCustomizer> customizers = this.restTemplateCustomizers.orderedStream()
.collect(Collectors.toList());
if (!CollectionUtils.isEmpty(customizers)) {
builder = builder.customizers(customizers);
}
return builder;
}
在项目中使用,配置RestTemplate
添加配置类, 配置 restTemplate
@Configuration
@ConditionalOnClass(RestTemplate.class)
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) {
return restTemplateBuilder
// 配置 readTimeout
.setReadTimeout(Duration.ofSeconds(5))
// 配置 连接超时
.setConnectTimeout(Duration.ofSeconds(2)).build();
}
}
项目中使用 只需要引入一下即可
@Autowired
private RestTemplate restTemplate;
restTemplate 重要参数
url: 请求地址
responseType: 返回值类型
uriVariables: url 变量值
Object request: 请求体;可以是个httpEntity;若为其他,则会创建一个httpEntity ,request为 httpEntity 的body
HttpEntity: 请求参数,可以设置body, headers
responseEnity: 请求返回值,包含具体的body, headers, httpstatus 等http信息
restTemplate GET POST PUT DELETE 操作 传参
get 请求
- getForObject
// 接收url 和 responseType
restTemplate.getForObject(JDBC_DEMO_URL + "/user/" + id, UserEntity.class);
// url传参; 使用 模板占位符 {index};进行传参,Object... uriVariables 按照index顺序进行传参
// 例如 url = /user/batch?ids={0}&ids={1}, 参数 uriVariables可变数组按照顺序传参;
// 注意: 这里的 collect 是我封装好的 = ‘?ids={index}’;例如 /user/batch?ids={0}&ids={1}
restTemplate.getForObject(JDBC_DEMO_URL + "/user/batch" + collect, List.class, ids);
// url传参, 同时模板占位符 {feild}进行传参, 使用 map uriVariables 进行参数赋值
// 例如 url = /user/batch?uName={name}&password={password};
// params = new Map(); put(name,name),put(password,password)
restTemplate.getForObject(JDBC_DEMO_URL + "/user/batch" + collect, List.class, params);
- getForEntity
getForEntity 和 getForObject 使用方式一样;只是返回的类型不一样;
getForEntity 返回 responseEntity, 可以有更具体的信息, body, headers, httpstatus 等信息;
ForENtity 和ForObject 请求使用是一样的 只是返回值不同;以下只使用其中的一种。
Post 请求
postForObject
public List<String> batchAddUser(@RequestBody List<UserEntity> userEntities) throws Exception {
return restTemplate.postForObject(JDBC_DEMO_URL + "/user/batch", userEntities, List.class);
}
参数userEntities; 是请求体,会封装到httpEntity 的body中;
post 请求的所有方法: 具体的参数可以参考restTemplate 重要参数
Put 请求
restTemplate.put(JDBC_DEMO_URL + "/user", userEntity);
delete 请求
Map<String, String> map = new HashMap<>();
map.put("id", id);
// 使用{field}占位符,进行参数映射
restTemplate.delete(JDBC_DEMO_URL + "/user/{id}", map