apache httpclient速成

2024-08-25 22:04
文章标签 apache httpclient 速成

本文主要是介绍apache httpclient速成,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

目录标题

  • 快速使用
  • 连接池
    • 参数
      • 连接池状态
      • 清除闲置连接evictIdleConnections
      • 删除过期连接 timeToLive 和evictExpiredConnections
  • 注意释放内存
    • 关闭流
  • http和netty的关系

导入依赖

     <dependency><groupId>org.apache.httpcomponents.client5</groupId><artifactId>httpclient5</artifactId><version>5.2.1</version></dependency>

快速使用

不关注其他,只需要发起请求,然后收到即可:

        CloseableHttpClient httpClient = HttpClients.createDefault(); // 创建clientHttpPost request = new HttpPost("https://www.baidu.com/"); // 请求信息request.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");RequestConfig config =RequestConfig.custom().setResponseTimeout(5000, TimeUnit.MILLISECONDS).build();request.setConfig(config); // 设置连接超时等参数// 发起调用String response = httpClient.execute(request, new HttpClientResponseHandler<String>() {@Overridepublic String handleResponse(ClassicHttpResponse classicHttpResponse) throws HttpException, IOException {System.out.println(classicHttpResponse.getCode());HttpEntity entity = classicHttpResponse.getEntity();InputStream content = entity.getContent();return EntityUtils.toString(entity);}});System.out.println(response);

连接池

http的连接池有什么用?
主要好处在于连接复用,减少创建/销毁 tcp 连接的开销(因为三次握手和四次挥手)。

需要注意的是:
1.http连接池不是万能的,过多的长连接会占用服务器资源,导致其他服务受阻
2.http连接池只适用于请求是经常访问同一主机(或同一个接口)的情况下
3.并发数不高的情况下资源利用率低下
4.httpclient是一个线程安全的类,没有必要由每个线程在每次使用时创建,全局保留一个即可。
比如:

    PoolingHttpClientConnectionManager poopManager = new PoolingHttpClientConnectionManager();poopManager.setMaxTotal(5); // 设置连接池最大连接数poopManager.setDefaultConnectionConfig( // 为所有路由设置连接参数ConnectionConfig.custom().setConnectTimeout(1000, TimeUnit.MILLISECONDS).setSocketTimeout(1000, TimeUnit.MILLISECONDS).build());poopManager.setMaxPerRoute( // 单独为一个路由设置最大连接数new HttpRoute(new HttpHost(InetAddress.getByName("www.baidu.com"), 443)),1);CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(poopManager).build();

参数

用如下代码作为示例。设置了连接池最大连接数是20,每个路由最大连接是2。
代码一共有四个路由,每一个网站都用一个异步线程调用10次

package com.example.springbootproject.httpclient;import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.HttpException;
import org.apache.hc.core5.http.io.HttpClientResponseHandler;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.pool.PoolStats;import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;public class HttpUtil {public static final CloseableHttpClient httpClient;public static final PoolingHttpClientConnectionManager poolManager;static {poolManager = new PoolingHttpClientConnectionManager();poolManager.setDefaultMaxPerRoute(2);poolManager.setMaxTotal(20);httpClient = HttpClients.custom()// 设置连接池管理.setConnectionManager(poolManager).build();}public static void main(String[] args) {HttpUtil.execute("http://www.baidu.com");HttpUtil.execute("https://juejin.cn/");HttpUtil.execute("https://www.zhihu.com/hot");HttpUtil.execute("https://www.bilibili.com/?utm_source=gold_browser_extension");// 创建一个定时线程池,包含单个线程ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);// 安排任务在初始延迟后执行,然后每隔一定时间打印状态executor.scheduleAtFixedRate(() -> {HttpUtil.httpPoolStats();}, 0, 1, TimeUnit.SECONDS);}public static void execute(String url) {for (int i = 0; i < 10; i++) {ExecutorService executor = Executors.newSingleThreadExecutor();executor.submit(() -> {HttpGet get = new HttpGet(url);CloseableHttpResponse response = null;try {Thread.sleep(1000);String execute = HttpUtil.httpClient.execute(get, new HttpClientResponseHandler<String>() {@Overridepublic String handleResponse(ClassicHttpResponse response) throws HttpException, IOException {return EntityUtils.toString(response.getEntity());}});} catch (Exception e) {throw new RuntimeException(e);}});}}public static void httpPoolStats() {// 获取所有路由的连接池状态PoolStats totalStats = poolManager.getTotalStats();System.out.println("Total status:" + totalStats.toString());}
}

连接池状态

PoolStats totalStats = poolManager.getTotalStats();打印出来是这样的[leased: 0; pending: 0; available: 0; max: 20]

  • leased:连接池正在使用的连接(Gets the number of persistent connections tracked by the connection manager currently being used to execute requests.The total number of connections in the pool is equal to {@code available} plus {@code leased})
  • pending:等待空闲连接的数量(Gets the number of connection requests being blocked awaiting a free connection. This can happen only if there are more worker threads contending for fewer connections.)
  • available:当前线程池空闲的连接数量(Gets the number idle persistent connections.)
  • max:最大允许的容量
    在这里插入图片描述
    可以看到,leased +available = 池子中的连接数。因为一共四个路由,每个路由最大可以有两个连接,所以一共是8个可用连接数。其中pending表示等待空闲的连接数量。

清除闲置连接evictIdleConnections

关闭闲置2s的连接
HttpClients.custom().evictIdleConnections(TimeValue.ofMilliseconds(2000))

或者自己开一个线程调用poolManager.closeIdle(TimeValue.ofMilliseconds(2000));
最终如下

在这里插入图片描述

删除过期连接 timeToLive 和evictExpiredConnections

timeToLive 的定义:
Defines the total span of time connections can be kept alive or execute requests.
timeToLive 推荐不设置值,使用默认即可。同时打开evictExpiredConnections,
这样会使用服务器返回的keepalive,只要在keepalive时间范围内,连接就不会关闭。


设置timetolive值
poolManager.setDefaultConnectionConfig( ConnectionConfig.custom().setTimeToLive(1000, TimeUnit.MILLISECONDS).build());
和打开删除过期的连接HttpClients.custom().evictExpiredConnections()

注意释放内存

关闭流

代码中有写到,接response转为字符串返回。其实这个entity.getContent()是一个流,需要被关闭。

  HttpEntity entity = classicHttpResponse.getEntity();String s = EntityUtils.toString(entity);

如何关闭?

  1. 手动关闭使用 EntityUtils.consume(entity);
  2. 实现一个HttpClientResponseHandler,就像我们上面中的那样。底层实现里面就已经调用过了。
    在这里插入图片描述

http和netty的关系

http是协议,netty是java的一个NIO的编程框架。比如使用netty我们搭建一个高性能的http 服务器,也可以用netty自定义协议通信。

参考:https://juejin.cn/post/7292029688998068243

这篇关于apache httpclient速成的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1106771

相关文章

Java使用HttpClient实现图片下载与本地保存功能

《Java使用HttpClient实现图片下载与本地保存功能》在当今数字化时代,网络资源的获取与处理已成为软件开发中的常见需求,其中,图片作为网络上最常见的资源之一,其下载与保存功能在许多应用场景中都... 目录引言一、Apache HttpClient简介二、技术栈与环境准备三、实现图片下载与保存功能1.

SpringBoot整合Apache Flink的详细指南

《SpringBoot整合ApacheFlink的详细指南》这篇文章主要为大家详细介绍了SpringBoot整合ApacheFlink的详细过程,涵盖环境准备,依赖配置,代码实现及运行步骤,感兴趣的... 目录1. 背景与目标2. 环境准备2.1 开发工具2.2 技术版本3. 创建 Spring Boot

Linux中修改Apache HTTP Server(httpd)默认端口的完整指南

《Linux中修改ApacheHTTPServer(httpd)默认端口的完整指南》ApacheHTTPServer(简称httpd)是Linux系统中最常用的Web服务器之一,本文将详细介绍如何... 目录一、修改 httpd 默认端口的步骤1. 查找 httpd 配置文件路径2. 编辑配置文件3. 保存

Spring Boot 整合 Apache Flink 的详细过程

《SpringBoot整合ApacheFlink的详细过程》ApacheFlink是一个高性能的分布式流处理框架,而SpringBoot提供了快速构建企业级应用的能力,下面给大家介绍Spri... 目录Spring Boot 整合 Apache Flink 教程一、背景与目标二、环境准备三、创建项目 & 添

Apache 高级配置实战之从连接保持到日志分析的完整指南

《Apache高级配置实战之从连接保持到日志分析的完整指南》本文带你从连接保持优化开始,一路走到访问控制和日志管理,最后用AWStats来分析网站数据,对Apache配置日志分析相关知识感兴趣的朋友... 目录Apache 高级配置实战:从连接保持到日志分析的完整指南前言 一、Apache 连接保持 - 性

apache的commons-pool2原理与使用实践记录

《apache的commons-pool2原理与使用实践记录》ApacheCommonsPool2是一个高效的对象池化框架,通过复用昂贵资源(如数据库连接、线程、网络连接)优化系统性能,这篇文章主... 目录一、核心原理与组件二、使用步骤详解(以数据库连接池为例)三、高级配置与优化四、典型应用场景五、注意事

解决Maven项目报错:failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.13.0的问题

《解决Maven项目报错:failedtoexecutegoalorg.apache.maven.plugins:maven-compiler-plugin:3.13.0的问题》这篇文章主要介... 目录Maven项目报错:failed to execute goal org.apache.maven.pl

深入理解Apache Kafka(分布式流处理平台)

《深入理解ApacheKafka(分布式流处理平台)》ApacheKafka作为现代分布式系统中的核心中间件,为构建高吞吐量、低延迟的数据管道提供了强大支持,本文将深入探讨Kafka的核心概念、架构... 目录引言一、Apache Kafka概述1.1 什么是Kafka?1.2 Kafka的核心概念二、Ka

使用Apache POI在Java中实现Excel单元格的合并

《使用ApachePOI在Java中实现Excel单元格的合并》在日常工作中,Excel是一个不可或缺的工具,尤其是在处理大量数据时,本文将介绍如何使用ApachePOI库在Java中实现Excel... 目录工具类介绍工具类代码调用示例依赖配置总结在日常工作中,Excel 是一个不可或缺的工http://

Apache伪静态(Rewrite).htaccess文件详解与配置技巧

《Apache伪静态(Rewrite).htaccess文件详解与配置技巧》Apache伪静态(Rewrite).htaccess是一个纯文本文件,它里面存放着Apache服务器配置相关的指令,主要的... 一、.htAccess的基本作用.htaccess是一个纯文本文件,它里面存放着Apache服务器