🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# 29.1.2. 连接生产环境数据库 生产环境的数据库连接可以通过池化的`DataSource`进行自动配置,下面是选取特定实现的算法: * 出于tomcat数据源连接池的优秀性能和并发,如果可用总会优先使用它。 * 如果HikariCP可用,我们将使用它。 * 如果Commons DBCP可用,我们将使用它,但生产环境不推荐。 * 最后,如果Commons DBCP2可用,我们将使用它。 如果使用`spring-boot-starter-jdbc`或`spring-boot-starter-data-jpa` 'starters',你会自动添加`tomcat-jdbc`依赖。 **注** 通过指定`spring.datasource.type`属性,你可以完全抛弃该算法,然后指定数据库连接池。如果你在tomcat容器中运行应用,由于默认提供`tomcat-jdbc`,这就很重要了。 **注** 其他的连接池可以手动配置,如果你定义自己的`DataSource` bean,自动配置是不会发生的。 DataSource配置被外部的`spring.datasource.*`属性控制,例如,你可能会在`application.properties`中声明以下片段: ```java spring.datasource.url=jdbc:mysql://localhost/test spring.datasource.username=dbuser spring.datasource.password=dbpass spring.datasource.driver-class-name=com.mysql.jdbc.Driver ``` **注** 你应该至少使用`spring.datasource.url`属性指定url,或Spring Boot尝试自动配置内嵌数据库。 **注** 你经常不需要指定`driver-class-name`,因为Spring boot可以从`url`推断大部分数据库。 **注** 对于将要创建的池化`DataSource`,我们需要验证是否有一个可用的`Driver`,所以在做其他事前会校验它。比如,如果你设置`spring.datasource.driver-class-name=com.mysql.jdbc.Driver`,然后该class加载出来,否则就会出错。 其他可选配置可以查看[DataSourceProperties](https://github.com/spring-projects/spring-boot/tree/v1.4.1.RELEASE/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceProperties.java),有些标准配置是跟实现无关的,对于实现相关的配置可以通过相应前缀进行设置(`spring.datasource.tomcat.*`,`spring.datasource.hikari.*`,`spring.datasource.dbcp.*`和`spring.datasource.dbcp2.*`),具体参考你使用的连接池文档。 例如,如果正在使用[Tomcat连接池](http://tomcat.apache.org/tomcat-8.0-doc/jdbc-pool.html#Common_Attributes),你可以自定义很多其他设置: ```text # Number of ms to wait before throwing an exception if no connection is available. spring.datasource.tomcat.max-wait=10000 # Maximum number of active connections that can be allocated from this pool at the same time. spring.datasource.tomcat.max-active=50 # Validate the connection before borrowing it from the pool. spring.datasource.tomcat.test-on-borrow=true ```