2016-04-12 79 views
1

this documentationSpring-boot + JDBC + HSQLDB:如何验证Spring Boot是否使用连接池?

29.1.1嵌入式数据库支持

春天开机即可自动配置嵌入式H2,HSQL和Derby数据库。 您不需要提供任何连接URL,只需在您要使用的嵌入式数据库中包含一个构建 依赖项。

29.1.2连接到生产数据库

生产数据库连接也可以被自动配置使用汇集 数据源。

DataSource配置由spring.datasource。*中的外部配置 属性控制。例如,你可能会在声明中application.properties以下 部分:

spring.datasource.url=jdbc:mysql://localhost/test 
spring.datasource.username=dbuser 
spring.datasource.password=dbpass 
spring.datasource.driver-class-name=com.mysql.jdbc.Driver 

[提示]您 往往不需要指定驱动程序类名,因为春季启动 可以推导出它对于来自url的大多数数据库。

[注意]对于要创建的共享数据源 ,我们需要能够验证有效的驱动程序类是否可用,因此我们在做任何事情之前检查它。 也就是说如果你设置 spring.datasource.driver-class-name = com.mysql.jdbc.Driver那么这个 类必须是可加载的。


如果我把我的application.properties以下文件:

spring.datasource.url=jdbc:hsqldb:file:db/organization-db 
spring.datasource.username=dbuser 
spring.datasource.password=dbpass 
spring.datasource.driver-class-name=org.hsqldb.jdbc.JDBCDriver 

会弹出开机自动配置池DataSource,因为我指定的spring.datasource.driver -class-name
或者它只是为没有连接池的嵌入式数据库驱动创建一个数据源?
如何确认Spring Boot是否使用连接池?

回答

1

我的理解是,只要类路径上有一个受支持的数据源类,spring-boot就会使用它,而如果没有指定,则使用tomcat作为首选项。

支持的数据源列表在DataSourceBuilder中给出,当前为tomcat,hikari,dbcp和dbcp2。

您可以通过从应用程序上下文中查找javax.sql.Datasource实现来验证其是否已创建,但我不明白为什么不这样做。

https://github.com/spring-projects/spring-boot/blob/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceBuilder.java

+0

感谢您的回答。 – Paul

4

感谢您的回答戴夫。我刚开始学习Spring框架,所以我正在修补它。这是我在MyApplication.main方法做了确认,如果春天开机使用连接池:

ApplicationContext context = SpringApplication.run(MyApplication.class); 
DataSource dataSource = context.getBean(javax.sql.DataSource.class); 
System.out.println("DATASOURCE = " + dataSource); 

而且我得到了以下的输出:

DATASOURCE = [email protected]{ConnectionPool[defaultAutoCommit=null; defaultReadOnly=null; defaultTransactionIsolation=-1; defaultCatalog=null; driverClassName=org.hsqldb.jdbcDriver; maxActive=100; maxIdle=100; minIdle=10; initialSize=10; maxWait=30000; testOnBorrow=false; testOnReturn=false; timeBetweenEvictionRunsMillis=5000; numTestsPerEvictionRun=0; minEvictableIdleTimeMillis=60000; testWhileIdle=false; testOnConnect=false; password=********; url=jdbc:hsqldb:mem:testdb; username=sa; validationQuery=null; validationQueryTimeout=-1; validatorClassName=null; validationInterval=30000; accessToUnderlyingConnectionAllowed=true; removeAbandoned=false; removeAbandonedTimeout=60; logAbandoned=false; connectionProperties=null; initSQL=null; jdbcInterceptors=null; jmxEnabled=true; fairQueue=true; useEquals=true; abandonWhenPercentageFull=0; maxAge=0; useLock=false; dataSource=null; dataSourceJNDI=null; suspectTimeout=0; alternateUsernameAllowed=false; commitOnReturn=false; rollbackOnReturn=false; useDisposableConnectionFacade=true; logValidationErrors=false; propagateInterruptState=false; ignoreExceptionOnPreLoad=false; } 

我也尝试过不同的配置使用application.properties文件和我的build.grade文件来确认Spring Boot是否会在自动配置DataSource时使用连接池a nd我发现Spring Boot的自动配置总是创建一个池化数据源。