springframework的RestTemplate配合连接池的使用

一、RestTemplate 介绍

从RestTemplate的注解类上可以看出:

  1. 从5.0版本开始,非阻塞。
  2. 支持异步和同步。
  3. 将在未来的版本中弃用,不会有主要的新功能。

二、RestTemplate的使用及示例

为方便理解,我简单画了下使用的UML图(如下):

2.1、jar包引入

该类在spring-web包里,如果你引用了spring-boot-start-web,则会自动引入。

2.2、定义httpClient线程池管理器

/**
 * 定义httpClient线程池管理器, 可以keep-alive不断开链接请求,这样速度会更快
 * @return
 */
@Bean
public HttpClientConnectionManager poolingConnectionManager() {
  PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager();
  //设置最大连接数
  poolingHttpClientConnectionManager.setMaxTotal(800);
  //设置每个路由基础的默认连接数
  poolingHttpClientConnectionManager.setDefaultMaxPerRoute(200);
  //设置检查永久链接可用性的间隔时间
  poolingHttpClientConnectionManager.setValidateAfterInactivity(30000);

  return poolingHttpClientConnectionManager;
}

 

2.3、定义httpClient建造器
 

/**
 * 定义httpClient建造器
 * @return
 */
@Bean
public HttpClient httpClient() {
  HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
  httpClientBuilder.setConnectionManager(poolingConnectionManager());
  return httpClientBuilder.build();
}

 

2.4、定义Http请求工厂
 

/**
 * 定义http请求工厂
 * @return
 */
@Bean
public HttpComponentsClientHttpRequestFactory httpRequestFactory() {
  HttpComponentsClientHttpRequestFactory httpComponentsClientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory();
  httpComponentsClientHttpRequestFactory.setHttpClient(httpClient());
  //下面三个参数的值一般设置成同样的值

  //以毫秒为单位确定超时时间,直到建立连接为止,0值表示超时值被解释为无限超时。
  httpComponentsClientHttpRequestFactory.setConnectTimeout(2000);
  //读取数据超时,就是socket的超时时间,超时后会SocketTimeoutException(ms)
  httpComponentsClientHttpRequestFactory.setReadTimeout(2000);
  //指从连接池获取连接请求超时时间(ms)
  httpComponentsClientHttpRequestFactory.setConnectionRequestTimeout(2000);

  return httpComponentsClientHttpRequestFactory;
}

2.5、初始化RestTemplate
 

/**
 * 初始化springframework的RestTemplate
 * @return
 */
@Bean
public RestTemplate restTemplate(){
  return new RestTemplate(httpRequestFactory());
}

2.6、具体的使用


2.6.1、测试方法

@Autowired
private RestTemplate restTemplate;

@Test
public void test01() {
  String url = "http://localhost:8081/test/login";
  HttpHeaders headers = new HttpHeaders();
  headers.setContentType(MediaType.APPLICATION_JSON);

  CarOnLineDTO info = new CarOnLineDTO();
  info.setCompanyId("1");
  info.setLicenseId("341203199210053136");
  info.setVehicleNo("浙B81KK5");
  info.setLoginTime(20200623211825L);
  info.setLongitude(121314489);
  info.setLatitude(29766730);
  info.setEncrypt((byte) 2);

  HttpEntity<String> request = new HttpEntity<>(JSON.toJSONString(info), headers);
//    ResponseEntity<CommonResponse> forEntity = restTemplate.getForEntity(url, CommonResponse.class);
  ResponseEntity<CommonResponse> response = restTemplate.postForEntity(url, request, CommonResponse.class);
  System.out.println(JSONObject.toJSONString(response.getBody()));
}

2.6.2、被模拟调用的controller方法
 

/**
 * 模拟登录
 *
 * @param object object
 * @return ResponseBean
 *
 * 备注:
 *  produces是指定返回值类型,比如赋值:"application/json;charset=UTF-8",可以指定多个类型
 *  consumes只指定请求指定类型,比如赋值:"application/json;charset=UTF-8",可以指定多个类型
 */
@PostMapping(value = "login", consumes = APPLICATION_JSON_UTF8_VALUE, produces = APPLICATION_JSON_UTF8_VALUE)
public ResponseBean handle(@RequestBody JSONObject object) throws InterruptedException {
   Thread.sleep(5000L);

   return new ResponseBean(200, "success");
}

2.6.3、调用结果展示

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot 默认使用 Apache HttpClient 作为 RestTemplate 的 HTTP 客户端。HttpClient 内部维护了一个连接池,可以提高连接的复用率和性能。 如果想要监听 RestTemplate连接池情况,可以通过 HttpClient 的连接池管理器进行实现。具体步骤如下: 1. 创建 HttpClient 的连接池管理器 ```java PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); ``` 2. 配置连接池参数 ```java connectionManager.setMaxTotal(200); // 最大连接数 connectionManager.setDefaultMaxPerRoute(20); // 每个路由的最大连接数 ``` 3. 创建 HttpClient 实例,并设置连接池管理器 ```java CloseableHttpClient httpClient = HttpClients.custom() .setConnectionManager(connectionManager) .build(); ``` 4. 将 HttpClient 实例设置到 RestTemplate 中 ```java RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient)); ``` 5. 添加连接池监视器 ```java connectionManager.getTotalStats(); // 获取连接池统计信息 connectionManager.closeIdleConnections(30, TimeUnit.SECONDS); // 关闭空闲连接 ``` 可以在定时任务中调用 `connectionManager.getTotalStats()` 获取连接池的统计信息,例如当前连接数、空闲连接数、请求等待时间等。同时可以使用 `connectionManager.closeIdleConnections()` 方法关闭空闲连接,避免长时间占用连接资源。 注意:以上代码只是示例,具体实现需要根据自己的业务场景进行调整。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值