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

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

基于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);
    }

}

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

时间: 2024-10-10 23:28:03

spring boot 基础篇 -- 阿里多数据源的相关文章

Spring boot 提高篇

Spring boot 提高篇 上篇文章介绍了Spring boot初级教程:构建微服务:Spring boot 入门篇,方便大家快速入门.了解实践Spring boot特性:本篇文章接着上篇内容继续为大家介绍spring boot的其它特性(有些未必是spring boot体系桟的功能,但是是spring特别推荐的一些开源技术本文也会介绍),对了这里只是一个大概的介绍,特别详细的使用我们会在其它的文章中来展开说明. github博文地址,阅读更佳 web开发 spring boot web开发

Spring Boot 基础

Spring Boot 基础 Spring Boot 项目(参考1) 提供了一个类似ASP.NET MVC的默认模板一样的标准样板,直接集成了一系列的组件并使用了默认的配置.使用Spring Boot 不会降低学习成本,甚至增加了学习成本,但显著降低了使用成本并提高了开发效率.如果没有Spring基础不建议直接上手. 1.基础项目 这里只关注基于Maven的项目构建,使用Spring Boot CLI命令行工具和Gradle构建方式请参考官网. (1)创建项目: 创建类型为quickstart的

Spring MVC 基础篇 1

Spring MVC基础篇  @RequestMapping使用 [email protected]RequestMapping 注解 进行请求映射 (1)指定Controller或者Method可以处理那些url请求. (2)适用范围:类定义上或者方法定义上都可以加. (3)在类定义处添加该注解是相对于WEB应用的根目录,在方法处是对类定义的请求处理的进一步细化.可以在类定义上没有添加该注解,但是方法定义上有该注解,此时 方法处的该注解标记的URL就是相对于WEB应用根目录. (4) 思考:此

Spring Boot基础-Spring Tool Suite工具的安装的安装

Spring Boot基础教程1-Spring Tool Suite工具的安装 Spring Boot基础教程2-RESTfull API简单项目的快速搭建 Spring Boot基础教程3-配置文件详解:Properties和YAML Spring Boot基础教程4-配置文件-多环境配置 Spring Boot基础教程5-日志配置-logback和log4j2 源码地址:https://github.com/roncoo/spring-boot-demo 1.工具下载地址: Eclipse:

Spring Boot 基础概述

上半年一直忙于工作,没有太多的时间去写文字,期间也比较关注 .net core 的发展,比较看好 asp.net core 的 OO 抽象设计,也参考了abp.zero 的设计.其实大多数情况平常的工作主要还是结合一些理论与技术框架快速实现:个人的时间就是成本,最近打算整理下 Spring Boot  的相关知识,也算是多一种选择吧 . 概述与目录 对于学习新的知识,我认为最快的方式就是先过一遍官方的文档,这一步很重要:后面再结合实际情况的运用就好了.所以我罗列了一些目录,应该覆盖了大多数的运用

构建微服务:Spring boot 入门篇

构建微服务:Spring boot 入门篇 什么是spring boot Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置.用我的话来理解,就是spring boot其实不是什么新的框架,它默认配置了很多框架的使用方式,就像maven整合了所有的jar包,spring boot整合了所有的框架(不知道这样比喻是否合适). 使用spring boot有什

spring boot 基础学习

构建微服务:Spring boot 入门篇 http://www.cnblogs.com/ityouknow/p/5662753.html SpringBoot入门系列:第一篇 Hello World http://blog.csdn.net/lxhjh/article/details/51711148 Spring Boot 快速入门 http://blog.csdn.net/xiaoyu411502/article/details/47864969 Spring Boot 官方文档学习(一)

Spring Boot基础-RESTfull API简单项目的快速搭建

Spring Boot基础教程1-Spring Tool Suite工具的安装 Spring Boot基础教程2-RESTfull API简单项目的快速搭建 Spring Boot基础教程3-配置文件详解:Properties和YAML Spring Boot基础教程4-配置文件-多环境配置 Spring Boot基础教程5-日志配置-logback和log4j2 源码地址:https://github.com/roncoo/spring-boot-demo 一.搭建一个简单的RESTfull

漫谈spring cloud 与 spring boot 基础架构

详情请交流  QQ  709639943 01.漫谈spring cloud 与 spring boot 基础架构 02.漫谈spring cloud分布式服务架构 03.Node.js入门到企业Web开发中的应用 04.精通高级RxJava 2响应式编程思想 05.Java秒杀系统方案优化 高性能高并发实战 06.Java深入微服务原理改造房产销售平台 07.快速上手Linux 玩转典型应用 08.快速上手Ionic3 多平台开发企业级问答社区 09.Java Spring Security开