用java写一个HttpClients的连接池实例,用PoolingHttpClientConnectionManager

177 篇文章 6 订阅

使用PoolingHttpClientConnectionManager可以创建一个具有连接池功能的HttpClient实例。下面是一个示例代码:

java
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;

public class HttpClientExample {
    public static void main(String[] args) {
        // 创建连接池管理器
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();

        // 设置最大连接数
        connectionManager.setMaxTotal(50);

        // 设置每个路由的最大连接数
        connectionManager.setDefaultMaxPerRoute(10);

        // 创建HttpClient对象,使用连接池管理连接
        CloseableHttpClient httpClient = HttpClients.custom()
                .setConnectionManager(connectionManager)
                .build();

        try {
            // 创建HttpGet请求
            HttpGet httpGet = new HttpGet("https://api.example.com");

            // 发送请求并获取响应
            CloseableHttpResponse response = httpClient.execute(httpGet);

            try {
                // 获取响应实体
                HttpEntity entity = response.getEntity();
                // 处理响应内容
                if (entity != null) {
                    String responseBody = EntityUtils.toString(entity);
                    System.out.println(responseBody);
                }
            } finally {
                // 关闭响应
                response.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭HttpClient连接
                httpClient.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
在这个示例中,使用PoolingHttpClientConnectionManager设置了连接池的最大连接数和每个路由的最大连接数。然后,通过HttpClients.custom().setConnectionManager(connectionManager).build()创建了一个带有连接池功能的HttpClient实例。可以根据需要进行进一步的配置和定制化。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以为您提供一个简单的Java数据库连接实现,此实现仅用于学习和演示目的。请注意,这不是一个完整的、生产就绪的连接实现,因为它缺少许多功能,例如:连接泄漏检测、空闲连接检测、最大连接数限制等。 首先,我们需要创建一个数据库连接类。以下是一个简单的实现: ```java import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class ConnectionPool { private String jdbcUrl; private String username; private String password; private List<Connection> connectionPool; private List<Connection> usedConnections = new ArrayList<>(); private final int INITIAL_POOL_SIZE = 10; public ConnectionPool(String jdbcUrl, String username, String password) { this.jdbcUrl = jdbcUrl; this.username = username; this.password = password; connectionPool = new ArrayList<>(INITIAL_POOL_SIZE); for (int i = 0; i < INITIAL_POOL_SIZE; i++) { try { Connection connection = DriverManager.getConnection(jdbcUrl, username, password); connectionPool.add(connection); } catch (SQLException e) { System.err.println(e.getMessage()); } } } public synchronized Connection getConnection() { Connection connection = null; if (connectionPool.size() > 0) { connection = connectionPool.remove(connectionPool.size() - 1); usedConnections.add(connection); } else { System.err.println("No more connections available."); } return connection; } public boolean releaseConnection(Connection connection) { boolean released = usedConnections.remove(connection); if (released) { connectionPool.add(connection); } return released; } public int getSize() { return connectionPool.size() + usedConnections.size(); } public void shutdown() throws SQLException { usedConnections.forEach(this::releaseConnection); for (Connection c : connectionPool) { c.close(); } connectionPool.clear(); } } ``` 接下来,我们来解释一下上面的代码: - `jdbcUrl`、`username` 和 `password` 存储了数据库连接的信息。 - `connectionPool` 存储了可用的连接,`usedConnections` 存储了当前正在使用的连接。 - `INITIAL_POOL_SIZE` 是连接的默认大小,可以根据需要进行修改。 - 在连接的构造函数中,我们创建了一定数量的连接,并将它们存储在连接中。 - `getConnection()` 方法从连接中获取一个可用的连接,如果连接为空,则返回 `null`。 - `releaseConnection()` 方法将一个连接释放回连接中。 - `getSize()` 方法返回连接的大小。 - `shutdown()` 方法关闭连接中的所有连接,并清空连接和正在使用的连接列表。 接下来,我们可以编一个测试类来测试连接的实现: ```java import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class TestConnectionPool { public static void main(String[] args) { String jdbcUrl = "jdbc:mysql://localhost:3306/test"; String username = "root"; String password = "password"; ConnectionPool connectionPool = new ConnectionPool(jdbcUrl, username, password); // Get a connection from the pool Connection connection = connectionPool.getConnection(); try { PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM users"); ResultSet resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { System.out.println(resultSet.getString("username")); } } catch (SQLException e) { System.err.println(e.getMessage()); } // Release the connection back to the pool connectionPool.releaseConnection(connection); // Shutdown the connection pool try { connectionPool.shutdown(); } catch (SQLException e) { System.err.println(e.getMessage()); } } } ``` 在上面的测试类中,我们首先创建了一个连接对象,并从中获取一个连接。然后,我们使用该连接执行一个查询,并将结果打印到控制台。最后,我们将连接释放回连接中,并关闭连接。 希望这可以帮助您开始编自己的数据库连接实现!

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值