码迷,mamicode.com
首页 > 编程语言 > 详细

spring boot 基础篇 -- 阿里多数据源

时间:2017-09-05 12:34:15      阅读:324      评论:0      收藏:0      [点我收藏+]

标签:dsa   done   frame   exce   redis   idle   core   iba   base   

这块是比较基础的配置,阿里数据库配置还是比较好用的,并且可以用来监控数据源的情况。废话不多说,下面看代码。

基于maven项目,在pom.xml中添加引用:

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.11</version>
        </dependency> 

配置文件如下:

server.port=9090
logging.level.tk.mybatis=TRACE

druid1.type=com.alibaba.druid.pool.DruidDataSource
druid1.url=jdbc:mysql://192.168.0.190:3306/bestPractices
druid1.driver-class=com.mysql.jdbc.Driver
druid1.username=root
druid1.password=youeDATA2016_
druid1.initial-size=1
druid1.min-idle=1
druid1.max-active=20
druid1.test-on-borrow=true
druid1.filters=stat,wall,log4j 
druid1.poolPreparedStatements=true  
druid1.datasource.maxPoolPreparedStatementPerConnectionSize=20  
druid1.datasource.logAbandoned=true 

druid2.type=com.alibaba.druid.pool.DruidDataSource
druid2.url=jdbc:mysql://192.168.0.190:3306/bestPracticesTwo
druid2.driver-class=com.mysql.jdbc.Driver
druid2.username=root
druid2.password=youeDATA2016_
druid2.initial-size=1
druid2.min-idle=1
druid2.max-active=20
druid2.test-on-borrow=true
druid2.filters=stat,wall,log4j
druid2.poolPreparedStatements=true  
druid2.datasource.maxPoolPreparedStatementPerConnectionSize=20  
druid2.datasource.logAbandoned=true

spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
mybatis.type-aliases-package=bp.model
mybatis.mapper-locations=classpath:mybatis/mybatis-config.xml
mapper.mappers=bp.util.MyMapper
#mapper.not-empty=false
#mapper.identity=MYSQL
pagehelper.helperDialect=mysql
pagehelper.reasonable=true 
pagehelper.supportMethodsArguments=true
pagehelper.dialect=com.github.pagehelper.dialect.helper.MySqlDialect
pagehelper.params=count=countSql
pagehelper.autoDialect=true  
pagehelper.closeConn=false  
pagehelper.offsetAsPageNum=true

spring.http.encoding.force=true
spring.redis.database= 0
spring.redis.host= 192.168.237.128
spring.redis.port= 6379
spring.redis.pool.max-active= 8
spring.redis.pool.max-idle= 8
spring.redis.pool.max-wait=-1
spring.redis.pool.min-idle=0
spring.redis.timeout= 1500

配置文件:数据源1

package bp.config;



import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import com.alibaba.druid.pool.DruidDataSource;




/**
 * 数据源1
 */
@Configuration
@EnableConfigurationProperties(DruidProperties1.class)
@AutoConfigureBefore(DataSourceAutoConfiguration.class)
@ConditionalOnClass(DruidDataSource.class)
@MapperScan(basePackages = "bp.mapper.mapper1", sqlSessionTemplateRef  = "SqlSessionTemplate1")
public class DataSource1Config {
    @Autowired
    private DruidProperties1 properties;

    @Bean(name = "DataSource1")
    @ConditionalOnProperty(prefix = "druid1", name = "url")
    @Primary
    public DataSource dataSource() throws SQLException {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(properties.getUrl());
        dataSource.setUsername(properties.getUsername());
        dataSource.setPassword(properties.getPassword());
        dataSource.setFilters(properties.getFilters());
        if (properties.getInitialSize() > 0) {
            dataSource.setInitialSize(properties.getInitialSize());
        }
        if (properties.getMinIdle() > 0) {
            dataSource.setMinIdle(properties.getMinIdle());
        }
        if (properties.getMaxActive() > 0) {
            dataSource.setMaxActive(properties.getMaxActive());
        }
        dataSource.setTestOnBorrow(properties.isTestOnBorrow());
        try {
            dataSource.init();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return dataSource;
    }

    @Bean(name = "SqlSessionFactory1")
    @Primary
    public SqlSessionFactory test1SqlSessionFactory(@Qualifier("DataSource1") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        bean.setDataSource(dataSource);
        bean.setConfigLocation(resolver.getResource("classpath:mybatis/mybatis-config.xml"));
        bean.setMapperLocations(resolver.getResources("bp/mapper/mapper1/*.xml"));
        return bean.getObject();
    }

    @Bean(name = "TransactionManager1")
    @Primary
    public DataSourceTransactionManager test1TransactionManager(@Qualifier("DataSource1") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "SqlSessionTemplate1")
    @Primary
    public SqlSessionTemplate test1SqlSessionTemplate(@Qualifier("SqlSessionFactory1") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}

数据源2:

package bp.config;


import java.sql.SQLException;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import com.alibaba.druid.support.spring.stat.DruidStatInterceptor;

import javax.annotation.Resource;
import javax.sql.DataSource;

/**
 * 数据源2
 */
@Configuration
@EnableConfigurationProperties(DruidProperties2.class)
@AutoConfigureBefore(DataSourceAutoConfiguration.class)
@ConditionalOnClass(DruidDataSource.class)
@MapperScan(basePackages = "bp.mapper.mapper2", sqlSessionTemplateRef  = "SqlSessionTemplate2")
public class DataSource2Config {

    @Autowired
    private DruidProperties2 properties;
    
    @Bean(name = "DataSource2")
    @ConditionalOnProperty(prefix = "druid2", name = "url")
    public DataSource dataSource() throws SQLException {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(properties.getUrl());
        dataSource.setUsername(properties.getUsername());
        dataSource.setPassword(properties.getPassword());
        dataSource.setFilters(properties.getFilters());
        if (properties.getInitialSize() > 0) {
            dataSource.setInitialSize(properties.getInitialSize());
        }
        if (properties.getMinIdle() > 0) {
            dataSource.setMinIdle(properties.getMinIdle());
        }
        if (properties.getMaxActive() > 0) {
            dataSource.setMaxActive(properties.getMaxActive());
        }
        dataSource.setTestOnBorrow(properties.isTestOnBorrow());
        try {
            dataSource.init();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return dataSource;
    }


    @Bean(name = "SqlSessionFactory2")
    public SqlSessionFactory test2SqlSessionFactory(@Qualifier("DataSource2") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        bean.setDataSource(dataSource);
        bean.setConfigLocation(resolver.getResource("classpath:mybatis/mybatis-config.xml"));
        bean.setMapperLocations(resolver.getResources("bp/mapper/mapper2/*.xml"));
        return bean.getObject();
    }

    @Bean(name = "TransactionManager2")
    public DataSourceTransactionManager test2TransactionManager(@Qualifier("DataSource2") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "SqlSessionTemplate2")
    public SqlSessionTemplate test2SqlSessionTemplate(@Qualifier("SqlSessionFactory2") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
    
}

启动项目就发现是双数据源了

spring boot 基础篇 -- 阿里多数据源

标签:dsa   done   frame   exce   redis   idle   core   iba   base   

原文地址:http://www.cnblogs.com/bestxyl/p/7477960.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!