SpringBoot Mybatisの統合時にDruidデータベース接続プールを使用

11879 ワード

SpringBootプロジェクトでは、次の依存度が増加します.
    
		
			org.mybatis.spring.boot
			mybatis-spring-boot-starter
			1.1.1
		

		
		
			mysql
			mysql-connector-java
			runtime
		

		
		
			com.alibaba
			druid
			1.0.26
		

resourceディレクトリの下でjdbc.propertiesプロファイルを作成し、次の構成を追加します.
#     
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false
spring.datasource.username=admin
spring.datasource.password=admin
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#      
#      ,  ,  
spring.datasource.initialSize=5  
spring.datasource.minIdle=5  
spring.datasource.maxActive=20  
#              
spring.datasource.maxWait=60000  
#              ,           ,     
spring.datasource.timeBetweenEvictionRunsMillis=60000  
#                 ,     
spring.datasource.minEvictableIdleTimeMillis=300000
#          sql
spring.datasource.validationQuery=select 'x'
#      true,     ,       
#          ,        timeBetweenEvictionRunsMillis,  validationQuery        
spring.datasource.testWhileIdle=true
#        validationQuery        
spring.datasource.testOnBorrow=false
#        validationQuery        
spring.datasource.testOnReturn=false
#    PSCache,      0,   0 ,poolPreparedStatements       true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
#         ,             ,      :
#       filter:stat
#     filter:log4j
#   sql   filter:wall
spring.datasource.filters=stat,log4j,wall

データソース構成クラスDataSourceConfig.javaを作成します.コードは次のとおりです.
package com.liao.mybatis;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 *    
 *
 * @author hongyangliao
 * @ClassName: DataSourceConfig
 * @Date 18-1-2   8:56
 */
@Configuration
@MapperScan("com.liao.**.dao")
public class DataSourceConfig {
    private static final Logger logger = LoggerFactory.getLogger(DataSourceConfig.class);

    @Autowired
    private JdbcConfig jdbcConfig;

    @Bean
    @Primary //    DataSource ,        DataSource
    public DataSource dataSource() {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUrl(jdbcConfig.getUrl());
        druidDataSource.setUsername(jdbcConfig.getUserName());
        druidDataSource.setPassword(jdbcConfig.getPassword());
        druidDataSource.setInitialSize(jdbcConfig.getInitialSize());
        druidDataSource.setMinIdle(jdbcConfig.getMinIdle());
        druidDataSource.setMaxActive(jdbcConfig.getMaxActive());
        druidDataSource.setTimeBetweenEvictionRunsMillis(jdbcConfig.getTimeBetweenEvictionRunsMillis());
        druidDataSource.setMinEvictableIdleTimeMillis(jdbcConfig.getMinEvictableIdleTimeMillis());
        druidDataSource.setValidationQuery(jdbcConfig.getValidationQuery());
        druidDataSource.setTestWhileIdle(jdbcConfig.isTestWhileIdle());
        druidDataSource.setTestOnBorrow(jdbcConfig.isTestOnBorrow());
        druidDataSource.setTestOnReturn(jdbcConfig.isTestOnReturn());
        druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(jdbcConfig.getMaxPoolPreparedStatementPerConnectionSize());
        try {
            druidDataSource.setFilters(jdbcConfig.getFilters());
        } catch (SQLException e) {
            if (logger.isInfoEnabled()) {
                logger.info(e.getMessage(), e);
            }
        }
        return druidDataSource;
    }


    /**
     * Jdbc   
     *
     * @author hongyangliao
     * @ClassName: JdbcConfig
     * @Date 18-1-2   9:00
     */
    @PropertySource(value = "classpath:jdbc.properties")
    @Component
    public static class JdbcConfig {
        /**
         *       
         */
        @Value("${spring.datasource.username}")
        private String userName;
        /**
         *     
         */
        @Value("${spring.datasource.driver-class-name}")
        private String driverClass;
        /**
         *      url
         */
        @Value("${spring.datasource.url}")
        private String url;
        /**
         *      
         */
        @Value("${spring.datasource.password}")
        private String password;

        /**
         *            
         */
        @Value("${spring.datasource.initialSize}")
        private int initialSize;

        /**
         *              
         */
        @Value("${spring.datasource.minIdle}")
        private int minIdle;

        /**
         *            
         */
        @Value("${spring.datasource.maxActive}")
        private int maxActive;

        /**
         *            
         */
        @Value("${spring.datasource.maxWait}")
        private long maxWait;

        /**
         *       
         */
        @Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
        private long timeBetweenEvictionRunsMillis;

        /**
         *             
         */
        @Value("${spring.datasource.minEvictableIdleTimeMillis}")
        private long minEvictableIdleTimeMillis;

        /**
         *          sql
         */
        @Value("${spring.datasource.validationQuery}")
        private String validationQuery;

        /**
         *          ,        timeBetweenEvictionRunsMillis,        
         */
        @Value("${spring.datasource.testWhileIdle}")
        private boolean testWhileIdle;

        /**
         *      ,        
         */
        @Value("${spring.datasource.testOnBorrow}")
        private boolean testOnBorrow;

        /**
         *      ,        
         */
        @Value("${spring.datasource.testOnReturn}")
        private boolean testOnReturn;

        /**
         * PSCache  
         */
        @Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")
        private int maxPoolPreparedStatementPerConnectionSize;

        /**
         *              
         */
        @Value("${spring.datasource.filters}")
        private String filters;

        public String getUserName() {
            return userName;
        }

        public void setUserName(String userName) {
            this.userName = userName;
        }

        public String getDriverClass() {
            return driverClass;
        }

        public void setDriverClass(String driverClass) {
            this.driverClass = driverClass;
        }

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }

        public int getInitialSize() {
            return initialSize;
        }

        public void setInitialSize(int initialSize) {
            this.initialSize = initialSize;
        }

        public int getMinIdle() {
            return minIdle;
        }

        public void setMinIdle(int minIdle) {
            this.minIdle = minIdle;
        }

        public int getMaxActive() {
            return maxActive;
        }

        public void setMaxActive(int maxActive) {
            this.maxActive = maxActive;
        }

        public long getMaxWait() {
            return maxWait;
        }

        public void setMaxWait(long maxWait) {
            this.maxWait = maxWait;
        }

        public long getTimeBetweenEvictionRunsMillis() {
            return timeBetweenEvictionRunsMillis;
        }

        public void setTimeBetweenEvictionRunsMillis(long timeBetweenEvictionRunsMillis) {
            this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
        }

        public long getMinEvictableIdleTimeMillis() {
            return minEvictableIdleTimeMillis;
        }

        public void setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis) {
            this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
        }

        public String getValidationQuery() {
            return validationQuery;
        }

        public void setValidationQuery(String validationQuery) {
            this.validationQuery = validationQuery;
        }

        public boolean isTestWhileIdle() {
            return testWhileIdle;
        }

        public void setTestWhileIdle(boolean testWhileIdle) {
            this.testWhileIdle = testWhileIdle;
        }

        public boolean isTestOnBorrow() {
            return testOnBorrow;
        }

        public void setTestOnBorrow(boolean testOnBorrow) {
            this.testOnBorrow = testOnBorrow;
        }

        public boolean isTestOnReturn() {
            return testOnReturn;
        }

        public void setTestOnReturn(boolean testOnReturn) {
            this.testOnReturn = testOnReturn;
        }

        public int getMaxPoolPreparedStatementPerConnectionSize() {
            return maxPoolPreparedStatementPerConnectionSize;
        }

        public void setMaxPoolPreparedStatementPerConnectionSize(int maxPoolPreparedStatementPerConnectionSize) {
            this.maxPoolPreparedStatementPerConnectionSize = maxPoolPreparedStatementPerConnectionSize;
        }

        public String getFilters() {
            return filters;
        }

        public void setFilters(String filters) {
            this.filters = filters;
        }
    }
}

Sessionファクトリ構成クラスSessionFactoryConfig.javaを作成します.コードは次のとおりです.
package com.liao.mybatis;

import java.io.IOException;

import javax.sql.DataSource;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement //        ,   xml      
public class SessionFactoryConfig {

    /**
     * mybatis     
     */
    private static String MYBATIS_CONFIG = "mybatis-config.xml";

    @Autowired
    private DataSource dataSource;


    /***
     *    sqlSessionFactoryBean
     *      configtion      .  
     *    mapper     
     *    datasource   
     *
     * @Title: createSqlSessionFactoryBean
     * @author: hongyangliao
     * @Date: 18-1-3   9:52
     * @param
     * @return org.mybatis.spring.SqlSessionFactoryBean sqlSessionFactoryBean  
     * @throws
     */
    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactoryBean createSqlSessionFactoryBean() throws IOException {
        SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
        //   mybatis configuration     
        sqlSessionFactory.setConfigLocation(new ClassPathResource(MYBATIS_CONFIG));
        //   datasource
        sqlSessionFactory.setDataSource(dataSource);
        return sqlSessionFactory;
    }
}