spring使用连接池
一、使用 HikariCP(Spring Boot 默认连接池)
1. 添加依赖(如果是 Spring Boot 默认支持的可以省略)
<dependency> <groupId>com.zaxxer</groupId> <artifactId>HikariCP</artifactId> </dependency>
2. 配置 application.yml
spring: datasource: url: jdbc:mysql://localhost:3306/test_db?useSSL=false&serverTimezone=UTC username: root password: 123456 driver-class-name: com.mysql.cj.jdbc.Driver hikari: minimum-idle: 5 # 最小空闲连接数 maximum-pool-size: 15 # 最大连接数 idle-timeout: 30000 # 空闲连接存活时间(ms) connection-timeout: 30000 # 获取连接的最大等待时间(ms) pool-name: MyHikariPool
二、使用 Druid(阿里巴巴)
1. 引入依赖
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.2.20</version> <!-- 请使用最新版本 --> </dependency>
2. 配置 application.yml
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
url: jdbc:mysql://localhost:3306/test_db?useSSL=false
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
druid:
initial-size: 5
min-idle: 5
max-active: 20
max-wait: 60000
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 300000
validation-query: SELECT 1 FROM DUAL
test-while-idle: true
test-on-borrow: false
test-on-return: false
pool-prepared-statements: true
max-pool-prepared-statement-per-connection-size: 20
3. 查看监控页面(可选)
@Configuration public class DruidConfig { @Bean public ServletRegistrationBean<StatViewServlet> druidServlet() { ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*"); bean.addInitParameter("loginUsername", "admin"); bean.addInitParameter("loginPassword", "123456"); return bean; } }

浙公网安备 33010602011771号