DBCP和Druid数据库连接池使用

需要用到的jar包,commons-dbcp2-*.jar、commons-logging-*.jar、commons-pool2-*.jar,*代表版本号

DataSourceTest类

package com.edu.zzu.Util;

import org.apache.commons.dbcp2.BasicDataSourceFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class DataSourceTest {
    private static final Log log = LogFactory.getLog(DataSourceTest.class);
    private static final String configFile = "dbcp.properties";

    private static DataSource dataSource;

    static {
        Properties properties = new Properties();
        try {
            properties.load(DataSourceTest.class.getClassLoader().getResourceAsStream(configFile));
            dataSource = BasicDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
           log.error("初始化连接池失败:"+e);
        }
    }

    public static Connection getConnection() {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            log.error("获取数据库连接失败:"+e);
        }
        return null;
    }

    public static void close(Connection conn) {
        try{
            if (conn != null || !conn.isClosed()) {
                conn.setAutoCommit(true);
                conn.close();
            }
        } catch (Exception e) {

        }
    }
}

dbcp.properties

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/lecture
username=root
password=123456
initialSize=10
maxActive=50
maxIdle=10
maxWait=10

DruidPool

package com.edu.zzu.Util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class DruidPool {
    private static DataSource dataSource;
    static {
        Properties prop = new Properties();
        try {
            prop.load(DataBaseConnection.class.getClassLoader().getResourceAsStream("dbcp.properties"));
        } catch (IOException e) {
            System.out.println("数据库配置文件丢失");
            e.printStackTrace();
        }
        try {
            dataSource = DruidDataSourceFactory.createDataSource(prop);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static Connection getConnection() {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
发布了274 篇原创文章 · 获赞 51 · 访问量 24万+
展开阅读全文

springboot2.0加入druid使用的还是Hikari

03-23

配置 ``` spring: datasource: type: com.alibaba.druid.pool.DruidDataSource master: jdbcUrl: jdbc:mysql://127.0.0.1:3306/spring_boot_learning?zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=utf-8 username: root password: root3306 driver-class-name: com.mysql.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource # 初始化大小,最小,最大 initialSize: 5 minIdle: 5 maxActive: 20 # 配置获取连接等待超时的时间 maxWait: 60000 # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 timeBetweenEvictionRunsMillis: 60000 # 配置一个连接在池中最小生存的时间,单位是毫秒 minEvictableIdleTimeMillis: 300000 validationQuery: SELECT 1 FROM DUAL testWhileIdle: true testOnBorrow: false testOnReturn: false # 打开PSCache,并且指定每个连接上PSCache的大小 poolPreparedStatements: true maxPoolPreparedStatementPerConnectionSize: 20 # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙 filters: stat,wall,log4j # 合并多个DruidDataSource的监控数据 #useGlobalDataSourceStat: true slave: jdbcUrl: jdbc:mysql://127.0.0.1:3306/spring_boot_learning_one?zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=utf-8 username: root password: root3306 driver-class-name: com.mysql.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource # 初始化大小,最小,最大 initialSize: 5 minIdle: 5 maxActive: 20 # 配置获取连接等待超时的时间 maxWait: 60000 # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 timeBetweenEvictionRunsMillis: 60000 # 配置一个连接在池中最小生存的时间,单位是毫秒 minEvictableIdleTimeMillis: 300000 validationQuery: SELECT 1 FROM DUAL testWhileIdle: true testOnBorrow: false testOnReturn: false # 打开PSCache,并且指定每个连接上PSCache的大小 poolPreparedStatements: true maxPoolPreparedStatementPerConnectionSize: 20 # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙 filters: stat,wall,log4j # 合并多个DruidDataSource的监控数据 #useGlobalDataSourceStat: true ``` 主数据源配置 ``` @Configuration @MapperScan(basePackages = "indi.xulala.dao.master", sqlSessionTemplateRef = "masterSqlSessionTemplate") public class MasterDataSourceConfig { @Bean(name = "masterDataSource") @ConfigurationProperties(prefix = "spring.datasource.master") @Primary public DataSource setDataSource() { return DataSourceBuilder.create().build(); } @Bean(name = "masterTransactionManager") @Primary public DataSourceTransactionManager setTransactionManager(@Qualifier("masterDataSource") DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } @Bean(name = "masterSqlSessionFactory") @Primary public SqlSessionFactory setSqlSessionFactory(@Qualifier("masterDataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml")); return bean.getObject(); } @Bean(name = "masterSqlSessionTemplate") @Primary public SqlSessionTemplate setSqlSessionTemplate(@Qualifier("masterSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception { return new SqlSessionTemplate(sqlSessionFactory); } } ``` 从数据源配置 ``` @Configuration @MapperScan(basePackages = "indi.xulala.dao.slave", sqlSessionTemplateRef = "slaveSqlSessionTemplate") public class SlaveDataSourceConfig { @Bean(name = "slaveDataSource") @ConfigurationProperties(prefix = "spring.datasource.slave") @Primary public DataSource setDataSource() { return DataSourceBuilder.create().build(); } @Bean(name = "slaveTransactionManager") @Primary public DataSourceTransactionManager setTransactionManager(@Qualifier("slaveDataSource") DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } @Bean(name = "slaveSqlSessionFactory") @Primary public SqlSessionFactory setSqlSessionFactory(@Qualifier("slaveDataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml")); return bean.getObject(); } @Bean(name = "slaveSqlSessionTemplate") @Primary public SqlSessionTemplate setSqlSessionTemplate(@Qualifier("slaveSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception { return new SqlSessionTemplate(sqlSessionFactory); } } ``` application ``` @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class}) @MapperScan(basePackages = {"indi.xulala.dao.master","indi.xulala.dao.slave"}) public class SpringBootLearningApplication { public static void main(String[] args) { SpringApplication.run(SpringBootLearningApplication.class, args); } } ``` 启动日志 ``` 07:48:27.764 [restartedMain] INFO o.s.j.e.a.AnnotationMBeanExporter - [afterSingletonsInstantiated,434] - Registering beans for JMX exposure on startup 07:48:27.765 [restartedMain] INFO o.s.j.e.a.AnnotationMBeanExporter - [autodetect,896] - Bean with name 'masterDataSource' has been autodetected for JMX exposure 07:48:27.765 [restartedMain] INFO o.s.j.e.a.AnnotationMBeanExporter - [autodetect,896] - Bean with name 'slaveDataSource' has been autodetected for JMX exposure 07:48:27.765 [restartedMain] INFO o.s.j.e.a.AnnotationMBeanExporter - [autodetect,896] - Bean with name 'statFilter' has been autodetected for JMX exposure 07:48:27.772 [restartedMain] INFO o.s.j.e.a.AnnotationMBeanExporter - [registerBeanInstance,669] - Located MBean 'masterDataSource': registering with JMX server as MBean [com.zaxxer.hikari:name=masterDataSource,type=HikariDataSource] 07:48:27.773 [restartedMain] INFO o.s.j.e.a.AnnotationMBeanExporter - [registerBeanInstance,669] - Located MBean 'slaveDataSource': registering with JMX server as MBean [com.zaxxer.hikari:name=slaveDataSource,type=HikariDataSource] 07:48:27.774 [restartedMain] INFO o.s.j.e.a.AnnotationMBeanExporter - [registerBeanInstance,669] - Located MBean 'statFilter': registering with JMX server as MBean [com.alibaba.druid.filter.stat:name=statFilter,type=StatFilter] ``` 测试日志 ``` 07:49:20.159 [main] INFO com.zaxxer.hikari.HikariDataSource - [getConnection,110] - HikariPool-1 - Starting... 07:49:20.694 [main] INFO com.zaxxer.hikari.HikariDataSource - [getConnection,123] - HikariPool-1 - Start completed. 07:49:20.742 [main] INFO com.zaxxer.hikari.HikariDataSource - [getConnection,110] - HikariPool-2 - Starting... 07:49:20.771 [main] INFO com.zaxxer.hikari.HikariDataSource - [getConnection,123] - HikariPool-2 - Start completed. 07:49:20.813 [Thread-3] INFO o.s.w.c.s.GenericWebApplicationContext - [doClose,989] - Closing org.springframework.web.context.support.GenericWebApplicationContext@38831718: startup date [Sat Mar 24 07:49:11 CST 2018]; root of context hierarchy 07:49:20.817 [Thread-3] INFO com.zaxxer.hikari.HikariDataSource - [close,381] - HikariPool-2 - Shutdown initiated... 07:49:20.833 [Thread-3] INFO com.zaxxer.hikari.HikariDataSource - [close,383] - HikariPool-2 - Shutdown completed. 07:49:20.834 [Thread-3] INFO com.zaxxer.hikari.HikariDataSource - [close,381] - HikariPool-1 - Shutdown initiated... 07:49:20.845 [Thread-3] INFO com.zaxxer.hikari.HikariDataSource - [close,383] - HikariPool-1 - Shutdown completed. ``` druid-spring-boot-starter版本1.1.9 问答

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览