目录
- 1、配置参数
- 1.1、基础配置
- 1.2、系统属性
- 1.3、一般参数
- 1.4、增强参数
- 2、使用
- 2.1、直接使用
- 2.1.1、引入依赖
- 2.1.2、使用例子
- 2.2、作为资源配置在 Tomcat 中
- 3.2、在 SpringBoot 中使用
- 3.1.1、引入依赖
- 3.1.2、单数据源
- 3.1.3、多数据源
前言:
Tomcat 连接池是从 Tomcat 7 开始重新编写的高并发连接池,用以取代以前 Tomcat 中使用的 DBCP 1 连接池,它可以配置在 Tomcat 中使用,也可以单独使用。本文主要介绍 Tomcat 连接池的基本使用,文中使用到的软件版本:Java 1.8.0_191、Tomcat 8.5.72、Spring Boot 2.3.12.RELEASE。
1、配置参数
1.1、基础配置
1.2、系统属性
1.3、一般参数
这些参数和 DBCP
一致,但有些默认值不一样。
默认的事务隔离级别
NONE、READ_COMMITTED、READ_UNCOMMITTED、
REPEATABLE_READ、SERIALIZABLE
默认的 catalog。(目录,类似于模式名,但比模式名更加抽象;
Oracle,MySQL 不支持,MS SQL Server = 数据库名)
连接校验的查询sql
如果指定,该 SQL 不需要返回结果,只要不抛 SQLException;如果没有指定,则通过调用 isValid() 方法进行校验。
连接属性,格式为: [propertyName=property;]*
"user" and "password" 将被除外,所以在此不需要包含这两个属性。
1.4、增强参数
jdbc 拦截器,需要继承 org.apache.tomcat.jdbc.pool.JdbcInterceptor;已存在的拦截器:
org.apache.tomcat.jdbc.pool.interceptor.ConnectionState 自动提交、只读、目录和事务隔离级别的跟踪
org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer statement的跟踪,在连接返回连接池时关闭它们
详细的说明可以参考官网文档:https://tomcat.apache.org/tomcat-8.5-doc/jdbc-pool.html
2、使用
2.1、直接使用
2.1.1、引入依赖
<dependency> <groupId>org.apache.tomcat</groupId> <artifactId>tomcat-jdbc</artifactId> <version>8.5.72</version> </dependency>
2.1.2、使用例子
package com.abc.demo.general.dbpool; import org.apache.tomcat.jdbc.pool.DataSource; import org.apache.tomcat.jdbc.pool.PoolProperties; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class TomcatPoolCase { public static void main(String[] args) { PoolProperties poolProperties = new PoolProperties(); poolProperties.setName("Tomcat连接池"); poolProperties.setUrl("jdbc:mysql://10.40.9.11:3306/mydb?useUnicode=true&characterEncoding=UTF-8"); poolProperties.setDriverClassName("com.mysql.cj.jdbc.Driver"); poolProperties.setUsername("root"); poolProperties.setPassword("123456"); poolProperties.setJmxEnabled(true); poolProperties.setTestWhileIdle(false); poolProperties.setTestOnBorrow(true); poolProperties.setValidationQuery("SELECT 1"); poolProperties.setTestOnReturn(false); poolProperties.setValidationInterval(30000); poolProperties.setTimeBetweenEvictionRunsMillis(30000); poolProperties.setMaxActive(100); poolProperties.setInitialSize(10); poolProperties.setMaxWait(10000); poolProperties.setRemoveAbandonedTimeout(60); poolProperties.setMinEvictableIdleTimeMillis(30000); poolProperties.setMinIdle(10); poolProperties.setLogAbandoned(true); poolProperties.setRemoveAbandoned(true); poolProperties.setJdbcInterceptors( "org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;" + "org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer"); DataSource datasource = new DataSource(); datasource.setPoolProperties(poolProperties); Connection connection = null; try { connection = datasource.getConnection(); Statement st = connection.createStatement(); ResultSet rs = st.executeQuery("select version()"); if (rs.next()) { System.out.println(rs.getString(1)); } } catch (SQLException e) { e.printStackTrace(); } finally { close(connection); } //实际使用中一般是在应用启动时初始化数据源,应用从数据源中获取连接;并不会关闭数据源。 datasource.close(); } private static void close(Connection connection) { if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
2.2、作为资源配置在 Tomcat 中
先把对应数据库的驱动包拷贝到 Tomcat
或应用的 lib
目录下,然后在 content.xml
中配置资源,
content.xml 可以在如下位置:
conf/context.xml
:针对所有的应用conf/Catalina/localhost
:针对单个应用,适合在Tomcat
外部部署应用{应用}/META-INFcontext.xml
:针对单个应用
配置资源的例子如下:
<Resource name="jdbc/testDb" auth="Container" type="javax.sql.DataSource" factory="org.apache.tomcat.jdbc.pool.DataSourceFactory" testWhileIdle="true" testOnBorrow="true" testOnReturn="false" validationQuery="SELECT 1" validationInterval="30000" timeBetweenEvictionRunsMillis="30000" maxActive="20" maxIdle="20" minIdle="5" maxWait="10000" initialSize="5" removeAbandonedTimeout="60" removeAbandoned="true" logAbandoned="true" minEvictableIdleTimeMillis="30000" jmxEnabled="true" jdbcInterceptors="org.apache.tomcat.jdbc.pool.interceptor.ConnectionState; org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer" username="root" password="123456" driverClassName="com.mysql.cj.jdbc.Driver" url="jdbc:mysql://10.40.9.11:3306/mydb?useUnicode=true&characterEncoding=UTF-8" />
可以通过 jndi
来查找该资源,这里通过 jsp 来演示查找方法:
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="UTF-8"%> <%@ page import="javax.naming.Context, javax.naming.InitialContext, javax.sql.DataSource, java.sql.*"%> <% Connection connection = null; try { InitialContext initialContext = new InitialContext(); Context context = (Context) initialContext.lookup("java:comp/env"); DataSource dataSource = (DataSource)context.lookup("jdbc/testDb"); connection = dataSource.getConnection(); Statement st = connection.createStatement(); ResultSet rs = st.executeQuery("select version()"); if (rs.next()) { System.out.println(rs.getString(1)); } } catch (Exception e) { e.printStackTrace(); } finally { if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } %> <html> <body> <h3>通过 jndi 查找数据源并获取数据库的版本信息</h3> </body> </html>
3.2、在 SpringBoot 中使用
3.1.1、引入依赖
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.12.RELEASE</version> <relativePath /> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> </dependency> <dependency> <groupId>org.apache.tomcat</groupId> <artifactId>tomcat-jdbc</artifactId> <version>8.5.72</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> </dependencies>
3.1.2、单数据源
application.yml 配置:
spring: datasource: tomcat-pool: name: Tomcat连接池 url: jdbc:mysql://10.40.9.11:3306/mydb?useUnicode=true&characterEncoding=UTF-8 driver-class-name: com.mysql.cj.jdbc.Driver username: root password: 123456 test-while-idle: true test-on-borrow: true validation-query: select 1 test-on-return: false validation-interval: 30000 time-between-eviction-runs-millis: 30000 max-active: 100 initial-size: 10 max-wait: 10000 remove-abandoned-timeout: 60 min-evictable-idle-time-millis: 30000 min-idle: 10 log-abandoned: true remove-abandoned: true jdbc-interceptors: org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer
数据源配置类:
package com.abc.demo.config; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.jdbc.DataSourceBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.sql.DataSource; @Configuration public class DataSourceConfig { @Bean("dataSource") @ConfigurationProperties(prefix = "spring.datasource.tomcat-pool") public DataSource dataSource() { return DataSourceBuilder.create().type(org.apache.tomcat.jdbc.pool.DataSource.class).build(); } }
使用:
@Autowired private DataSource dataSource;
3.1.3、多数据源
application.yml 配置:
spring: datasource: tomcat-pool: db1: name: Tomcat连接池 url: jdbc:mysql://10.40.9.11:3306/mydb?useUnicode=true&characterEncoding=UTF-8 driver-class-name: com.mysql.cj.jdbc.Driver username: root password: 123456 test-while-idle: true test-on-borrow: true validation-query: select 1 test-on-return: false validation-interval: 30000 time-between-eviction-runs-millis: 30000 max-active: 100 initial-size: 10 max-wait: 10000 remove-abandoned-timeout: 60 min-evictable-idle-time-millis: 30000 min-idle: 10 log-abandoned: true remove-abandoned: true jdbc-interceptors: org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer db2: name: Tomcat连接池 url: jdbc:mysql://10.110.74.187:3306/egmp?useUnicode=true&characterEncoding=UTF-8 driver-class-name: com.mysql.cj.jdbc.Driver username: root password: InsYR0ot187! test-while-idle: true test-on-borrow: true validation-query: select 1 test-on-return: false validation-interval: 30000 time-between-eviction-runs-millis: 30000 max-active: 100 initial-size: 10 max-wait: 10000 remove-abandoned-timeout: 60 min-evictable-idle-time-millis: 30000 min-idle: 10 log-abandoned: true remove-abandoned: true jdbc-interceptors: org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer
数据源配置类:
package com.abc.demo.config; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.jdbc.DataSourceBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.sql.DataSource; @Configuration public class DataSourceConfig { @Bean("dataSource1") @ConfigurationProperties(prefix = "spring.datasource.tomcat-pool.db1") public DataSource dataSource1() { return DataSourceBuilder.create().type(org.apache.tomcat.jdbc.pool.DataSource.class).build(); } @Bean("dataSource2") @ConfigurationProperties(prefix = "spring.datasource.tomcat-pool.db2") public DataSource dataSource2() { return DataSourceBuilder.create().type(org.apache.tomcat.jdbc.pool.DataSource.class).build(); } }
使用:
@Autowired @Qualifier("dataSource1") private DataSource dataSource1; @Autowired @Qualifier("dataSource2") private DataSource dataSource2;
到此这篇关于 Java 数据库连接池 Tomcat介绍的文章就介绍到这了,更多相关 Java连接池 Tomcat内容请搜索自由互联以前的文章或继续浏览下面的相关文章希望大家以后多多支持自由互联!