在 Java 里,“网络连接池”通常指 数据库连接池(JDBC Pool) 或 HTTP 连接池(如 Apache HttpClient / OkHttp)。下面我分几种常见场景给你讲清楚 怎么用。
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>5.0.1</version>
</dependency>
HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:mysql://localhost:3306/test");
config.setUsername("root");
config.setPassword("123456");
config.setMaximumPoolSize(10);
HikariDataSource dataSource = new HikariDataSource(config);
try (Connection conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement("SELECT * FROM user");
ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
System.out.println(rs.getString("name"));
}
}
✅ 连接用完会自动归还池中
Spring Boot 默认使用 HikariCP
spring:
datasource:
url: jdbc:mysql://localhost:3306/test
username: root
password: 123456
hikari:
maximum-pool-size: 10
@Autowired
DataSource dataSource;
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
</dependency>
PoolingHttpClientConnectionManager cm =
new PoolingHttpClientConnectionManager();
cm.setMaxTotal(100);
cm.setDefaultMaxPerRoute(20);
CloseableHttpClient httpClient = HttpClients.custom()
.setConnectionManager(cm)
.build();
HttpGet get = new HttpGet("https://example.com");
try (CloseableHttpResponse response = httpClient.execute(get)) {
System.out.println(response.getCode());
}
OkHttpClient client = new OkHttpClient.Builder()
.connectionPool(new ConnectionPool(5, 5, TimeUnit.MINUTES))
.build();
❌ 不关闭 Connection
❌ 池大小设置过大
❌ 长时间不用不回收
如果你指的是 某种特定池(Redis / Netty / WebSocket / 自定义 Socket),告诉我具体场景,我可以直接给你示例代码。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。