我又回来更新RestTemplate了,前面更完之后忽然发现还漏了两个常用的场景,连接池的配置以及错误重试,这就迅速的把这个补上;本篇主要介绍RestTemplate如何设置连接池
I. 项目搭建
本项目基于SpringBoot 2.2.1.RELEASE + maven 3.5.3 + idea进行开发
1. pom依赖
核心pom依赖如下
1 | <dependency> |
请注意,我们这里引入的依赖,多了一个httpclient,在下面的连接池配置中,主要借助它的连接池管理来创建HttpClient对象
II. 使用姿势
1. 连接池配置
一般来讲,借助httpcomponents这个包进行连接池配置时,可以分为三步
初始化连接池管理类
1 | // 连接池管理 |
HttpClient构造器
1 | HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); |
RestTemplate RequestFactory创建
1 | HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); |
到这里基本上就是前面的初始化RestTemplate的环节了
1 | // 创建restemplate对象,并制定 RequestFactory |
2. OkHttp方式
对于RestTemplate的HttpClient执行库,除了上面的httpcomponents之外,还有一个OkHttp目前也是大受欢迎,如果我们使用OkHttp,那么可以怎么设置呢?
首先依然是引入依赖
1 | <dependency> |
其次和上面三步骤差不多的设置
初始化连接池
1 | // 设置连接池参数,最大空闲连接数200,空闲连接存活时间10s |
创建OkHttpClient
注意这里和上面是有区别的,前面是构建HttpClient构造器,而这里直接生成了一个OkHttpClient,内置连接池
1 | OkHttpClient okHttpClient = |
RestTemplate RequestFactory创建
1 | ClientHttpRequestFactory factory = new OkHttp3ClientHttpRequestFactory(okHttpClient); |
最后就是创建RestTemplate了
1 | RestTemplate restTemplate = new RestTemplate(); |
II. 其他
0. 项目&系列博文
博文
- 【WEB系列】RestTemplate之文件上传
- 【WEB系列】AsyncRestTemplate之异步非阻塞网络请求介绍篇
- 【WEB系列】RestTemplate之非200状态码信息捕获
- 【WEB系列】RestTemplate之Basic Auth授权
- 【WEB系列】RestTemplate之代理访问
- 【WEB系列】RestTemplate之超时设置
- 【WEB系列】RestTemplate之中文乱码问题fix
- 【WEB系列】RestTemplate之自定义请求头
- 【WEB系列】RestTemplate基础用法小结
源码
- 工程:https://github.com/liuyueyi/spring-boot-demo
- 源码: https://github.com/liuyueyi/spring-boot-demo/tree/master/spring-boot/221-web-resttemplate
1. 一灰灰Blog
尽信书则不如,以上内容,纯属一家之言,因个人能力有限,难免有疏漏和错误之处,如发现bug或者有更好的建议,欢迎批评指正,不吝感激
下面一灰灰的个人博客,记录所有学习和工作中的博文,欢迎大家前去逛逛
- 一灰灰Blog个人博客 https://blog.hhui.top
- 一灰灰Blog-Spring专题博客 http://spring.hhui.top
