β

Spring Boot中得到当前数据库的连接池

用spring boot开发应用程序确实简单了很多,有时候需要在运行过程中得到当前数据库连接池的情况。其实spring  boot 也提供了很方便的方法,对于连接池,可以用spirng boot 默认的tomcat, 也有DBCP类型的。看项目的具体情况了,直接上代码,其实只需要注入java.sql.Datasource 这个类就可以得到连接池的情况了。
package com.yihaomen;
import javax.sql.DataSource;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@EnableTransactionManagement()
@MapperScan("com.yihaomen.*")
@SpringBootApplication
public class Application extends SpringBootServletInitializer implements CommandLineRunner {    
    @Autowired
    DataSource dataSource;    
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
    @Override
    public void run(String... arg0) throws Exception {        
        System.out.println("DATASOURCE = " + dataSource);
    }    
}

有打印出来的连接池情况:
org.apache.tomcat.jdbc.pool.DataSource@1897dab{ConnectionPool[defaultAutoCommit=null; defaultReadOnly=null; defaultTransactionIsolation=-1; defaultCatalog=null; driverClassName=com.mysql.jdbc.Driver; maxActive=100; maxIdle=100; minIdle=10; initialSize=10; maxWait=30000; testOnBorrow=true; testOnReturn=false; timeBetweenEvictionRunsMillis=5000; numTestsPerEvictionRun=0; minEvictableIdleTimeMillis=60000; testWhileIdle=false; testOnConnect=false; password=********; url=jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true; username=root; validationQuery=Select 1; validationQueryTimeout=-1; validatorClassName=null; validationInterval=3000; 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; }

发表评论