SpringBoot 提供了多种数据库连接配置方式,支持主流的关系型数据库和 NoSQL 数据库。本文详细介绍 MySQL 数据库的连接配置方法、连接池配置、多数据源配置以及最佳实践。
application.yml 配置
spring:
# 数据源配置
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/moon?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=Asia/Shanghai
username: root
password: 123456
hikari:
minimum-idle: 5 # 最小空闲连接数,建议设置为5-10
maximum-pool-size: 20 # 最大连接池大小,根据应用负载调整,通常10-30
auto-commit: true # 自动提交
idle-timeout: 30000 # 空闲连接超时时间(毫秒), 默认10分钟
pool-name: DatebookHikariCP # 连接池名称
max-lifetime: 1800000 # 连接最大生命周期(毫秒) 建议小于数据库的wait_timeout
connection-timeout: 30000 # 连接超时时间(毫秒) 默认 30 秒
connection-test-query: SELECT 1 # 测试连接查询
# 启用重试机制
retry:
enabled: true
Spring Boot 默认使用 HikariCP 连接池,无需额外依赖,直接配置即可。
重要参数说明:
- minimum-idle: 最小空闲连接数,建议设置为5-10
- maximum-pool-size: 最大连接数,根据应用负载调整
- connection-timeout: 获取连接超时时间,默认30秒
- idle-timeout: 空闲连接超时时间,默认10分钟
- max-lifetime: 连接最大生命周期,建议小于数据库的wait_timeout
最大连接数 maximum-pool-size 建议根据应用负载情况进行调整
- 小型应用,并发用户量 < 100, 最大连接数建议设置为 20~30
- 中型应用,并发用户量 100-1000, 最大连接数建议设置为 50-100
- 大型应用,并发用户量 > 1000, 最大连接数建议设置为100~200,并根据应用负载、压测情况和数据库性能进行调整
但是连接也不是越多越好,连接数过多会导致数据库性能下降,同时也会占用数据库的资源(每个连接消耗 2~8K 的内存)。
自定义连接池配置
@Configuration
public class DataSourceConfig {
@Bean
@ConfigurationProperties(prefix = "spring.datasource.hikari")
public HikariConfig hikariConfig() {
return new HikariConfig();
}
@Bean
@Primary
public DataSource dataSource(HikariConfig hikariConfig) {
return new HikariDataSource(hikariConfig);
}
}
多数据源配置
配置文件
spring:
datasource:
# 主数据源
primary:
url: jdbc:mysql://localhost:3306/db1
username: root
password: password
driver-class-name: com.mysql.cj.jdbc.Driver
hikari:
maximum-pool-size: 20
minimum-idle: 5
# 从数据源
secondary:
url: jdbc:mysql://localhost:3306/db2
username: root
password: password
driver-class-name: com.mysql.cj.jdbc.Driver
hikari:
maximum-pool-size: 15
minimum-idle: 3
多数据源配置类
@Configuration
public class MultiDataSourceConfig {
@Primary
@Bean(name = "primaryDataSource")
@ConfigurationProperties(prefix = "spring.datasource.primary")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "secondaryDataSource")
@ConfigurationProperties(prefix = "spring.datasource.secondary")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create().build();
}
@Primary
@Bean(name = "primaryJdbcTemplate")
public JdbcTemplate primaryJdbcTemplate(@Qualifier("primaryDataSource") DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
@Bean(name = "secondaryJdbcTemplate")
public JdbcTemplate secondaryJdbcTemplate(@Qualifier("secondaryDataSource") DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
}
使用多数据源
@Service
public class UserService {
@Autowired
@Qualifier("primaryJdbcTemplate")
private JdbcTemplate primaryJdbcTemplate;
@Autowired
@Qualifier("secondaryJdbcTemplate")
private JdbcTemplate secondaryJdbcTemplate;
public void saveUser(User user) {
// 使用主数据源
primaryJdbcTemplate.update("INSERT INTO users (name, email) VALUES (?, ?)",
user.getName(), user.getEmail());
}
public List<User> getUsers() {
// 使用从数据源
return secondaryJdbcTemplate.query("SELECT * FROM users",
new BeanPropertyRowMapper<>(User.class));
}
}
事务配置
基本事务配置
@Configuration
@EnableTransactionManagement
public class TransactionConfig {
@Bean
public PlatformTransactionManager transactionManager(DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
}
分布式事务配置
Maven 依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jta-atomikos</artifactId>
</dependency>
spring-boot-starter-jta-atomikos 是Spring Boot提供的分布式事务管理器启动器,主要用于处理分布式事务。
如果项目中有多个数据源,且涉及到跨多个数据源的事务时,需要通过 spring-boot-starter-jta-atomikos 配置分布式事务管理器,保证分布式事务的 ACID.
配置文件
spring:
jta:
atomikos:
properties:
enable-logging: true
log-base-name: transaction-log
max-timeout: 300000
default-jta-timeout: 300000

重要参数说明

Java 配置
@Configuration
public class AtomikosConfig {
@Bean
public AtomikosJtaPlatform atomikosJtaPlatform() {
return new AtomikosJtaPlatform();
}
@Bean(initMethod = "init", destroyMethod = "close")
public UserTransactionService userTransactionService() {
Properties properties = new Properties();
properties.setProperty("com.atomikos.icatch.tm_unique_name", "myTM");
properties.setProperty("com.atomikos.icatch.default_jta_timeout", "30000");
properties.setProperty("com.atomikos.icatch.max_timeout", "300000");
properties.setProperty("com.atomikos.icatch.log_base_dir", "./logs");
UserTransactionServiceImp service = new UserTransactionServiceImp(properties);
return service;
}
}
@Configuration
@EnableTransactionManagement
public class DataSourceConfig {
@Primary
@Bean("primaryDataSource")
public DataSource primaryDataSource() {
AtomikosDataSourceBean dataSource = new AtomikosDataSourceBean();
dataSource.setXaDataSourceClassName("com.mysql.cj.jdbc.MysqlXADataSource");
// 设置连接属性
return dataSource;
}
}
6. 配置加密
6.1 使用 Jasypt 加密敏感信息
Maven 依赖
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>3.0.4</version>
</dependency>
配置文件
jasypt:
encryptor:
password: mySecretKey
algorithm: PBEWITHHMACSHA512ANDAES_256
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb
username: root
password: ENC(encrypted_password_here)
加密工具类
@Component
public class JasyptUtil {
@Autowired
private StringEncryptor encryptor;
public String encrypt(String plainText) {
return encryptor.encrypt(plainText);
}
public String decrypt(String encryptedText) {
return encryptor.decrypt(encryptedText);
}
}
监控和健康检查
Actuator 数据源监控
Maven 依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
配置文件
management:
endpoints:
web:
exposure:
include: health,info,metrics,env
endpoint:
health:
show-details: always
自定义健康检查
@Component
public class DatabaseHealthIndicator implements HealthIndicator {
@Autowired
private DataSource dataSource;
@Override
public Health health() {
try (Connection connection = dataSource.getConnection()) {
if (connection.isValid(1)) {
return Health.up()
.withDetail("database", "Available")
.withDetail("validationQuery", "SELECT 1")
.build();
} else {
return Health.down()
.withDetail("database", "Not Available")
.build();
}
} catch (Exception e) {
return Health.down()
.withDetail("database", "Connection failed")
.withDetail("error", e.getMessage())
.build();
}
}
}
使用连接池监控
@Bean
public MeterRegistryCustomizer<MeterRegistry> hikariMetricsCustomizer() {
return registry -> {
registry.config().meterFilter(
MeterFilter.deny(id -> id.getName().startsWith("hikari") &&
id.getTag("pool") == null));
};
}
连接池耗尽处理
@Component
public class DataSourceMonitor {
@EventListener
public void handleDataSourceEvent(DataSourcePoolMetrics event) {
if (event.getActive() >= event.getMax() * 0.9) {
// 发送告警
alertService.sendAlert("Connection pool nearly exhausted");
}
}
}
文章标签
冬眠
博主专注于技术、阅读与思考。在这里记录学习、思考与生活。
系列:SpringBoot 配置
第 1 篇,共 3 篇
