Tomcat Connection pool in Spring Boot

Add below jar in build.gradle

implementation 'org.apache.tomcat:tomcat-jdbc:9.0.33'

application.properties

server.port=9090
#logging.level.org.springframework=DEBUG

#DataSource Setting
spring.datasource.type = org.apache.tomcat.jdbc.pool.DataSource
spring.datasource.url=jdbc:mysql://localhost:3306/mysql
spring.datasource.username=tyson
spring.datasource.password=tyson
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

#Tomcat Connection Pool settings
spring.datasource.tomcat.initial-size=15
spring.datasource.tomcat.max-wait=10000
spring.datasource.tomcat.max-active=50
spring.datasource.tomcat.max-idle=15
spring.datasource.tomcat.min-idle=8
spring.datasource.tomcat.default-auto-commit=true
spring.datasource.tomcat.test-on-borrow=true
spring.datasource.tomcat.test-on-return=true
spring.datasource.tomcat.test-on-connect=true

Code :

	@Autowired
	DataSource dataSource;
	
	@Bean
	public JdbcTemplate jdbcTemplate() throws SQLException {
		System.out.println(dataSource);
		JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
		return jdbcTemplate;
	}

You can also create Connection pool via Java Code :

//import org.apache.tomcat.jdbc.pool.DataSource;
//import org.apache.tomcat.jdbc.pool.PoolProperties;

	@Bean
	public JdbcTemplate jdbcTemplate() throws SQLException {
		System.out.println(dataSource);
		JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
		return jdbcTemplate;
	}

	@Bean
	public DataSource getTomcatDataSource() {
		PoolProperties p = new PoolProperties();
		p.setUrl("jdbc:mysql://localhost:3306/mysql");
		p.setDriverClassName("com.mysql.cj.jdbc.Driver");
		p.setUsername("tyson");
		p.setPassword("tyson");
		p.setJmxEnabled(true);
		p.setTestWhileIdle(false);
		p.setTestOnBorrow(true);
		p.setValidationQuery("SELECT 1");
		p.setTestOnReturn(false);
		p.setValidationInterval(30000);
		p.setTimeBetweenEvictionRunsMillis(30000);
		p.setMaxActive(100);
		p.setInitialSize(10);
		p.setMaxWait(10000);
		p.setRemoveAbandonedTimeout(60);
		p.setMinEvictableIdleTimeMillis(30000);
		p.setMinIdle(10);
		p.setLogAbandoned(true);
		p.setRemoveAbandoned(true);
		p.setJdbcInterceptors("org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;"
				+ "org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer");
		DataSource datasource = new DataSource();
		datasource.setPoolProperties(p);
		return datasource;
	}

You can check if Tomcat connection pool is created at startup when you see below message on log

Read Me :

https://tomcat.apache.org/tomcat-8.0-doc/jdbc-pool.html
http://tomcat.apache.org/tomcat-8.0-doc/jdbc-pool.html#Common_Attributes

Leave a Comment