springboot - 多数据源配置 - 分页插件

疑点:mybatis分页方言,方式一用代码区别了,方式二看起来并没有区别。

方式一:

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.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
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.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;
import com.alibaba.druid.pool.DruidDataSource;
import com.giveu.product.config.properties.DruidProperties;

@Component
@ConfigurationProperties(prefix = "spring.datasource.fn")
@Configuration
@MapperScan(basePackages="com.giveu.product.mapper", sqlSessionTemplateRef="fnSqlSessionTemplate")
public class DataSourceConfig extends DruidProperties{
    @Bean(name = "fnDataSource")
    @Primary
    public DruidDataSource dataSource(DataSourceProperties properties) {
        DruidDataSource dataSource = new DruidDataSource();
        this.config(dataSource);
        return dataSource;
    }
    @Bean(name = "fnSqlSessionFactory")
    @Primary
    public SqlSessionFactory sqlSessionFactory(@Qualifier("fnDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(
            "classpath:com/giveu/product/mapper/mapping/*.xml"));
        return bean.getObject();
    }
    @Bean(name = "fnTransactionManager")
    @Primary
    public DataSourceTransactionManager transactionManager(@Qualifier("fnDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
    @Bean(name = "fnSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("fnSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}




import com.alibaba.druid.pool.DruidDataSource;
import com.github.pagehelper.PageInterceptor;
import com.giveu.product.config.properties.DruidProperties;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.ibatis.plugin.Interceptor;
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.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "spring.datasource.fundpush")
@Configuration
@MapperScan(basePackages="com.giveu.product.fundpush.mapper", sqlSessionTemplateRef="fundPushSqlSessionTemplate")
public class FundPushDataSourceConfig extends DruidProperties {
    @Bean(name = "fundPushDataSource")
    public DruidDataSource fundPushDataSource(DataSourceProperties properties) {
        DruidDataSource dataSource = new DruidDataSource();
        this.config(dataSource);
        return dataSource;
    }
    @Bean(name = "fundPushSqlSessionFactory")
    public SqlSessionFactory fundPushSqlSessionFactory(@Qualifier("fundPushDataSource") DataSource dataSource)
        throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(
        	"classpath:com/giveu/product/fundpush/mapper/mapping/*.xml"));
        Interceptor interceptor = new PageInterceptor();
        Properties properties = new Properties();
        properties.setProperty("helperDialect", "mysql");
        interceptor.setProperties(properties);
        bean.setPlugins(new Interceptor[] {interceptor});
        return bean.getObject();
    }
    @Bean(name = "fundPushTransactionManager")
    public DataSourceTransactionManager fundPushTransactionManager(@Qualifier("fundPushDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
    @Bean(name = "fundPushSqlSessionTemplate")
    public SqlSessionTemplate fundPushSqlSessionTemplate(
        @Qualifier("fundPushSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}




import com.alibaba.druid.pool.DruidDataSource;
import com.giveu.common.utils.DBUtil;
import java.sql.SQLException;
import java.util.Map;

public class DruidProperties {
	private String url;
	private String username;
	private String password;
	private String driverClassName;
	private String api;
	private Integer initialSize = 2;
	private Integer minIdle = 1;
	private Integer maxActive = 20;
	private Integer maxWait = 60000;
	private Integer timeBetweenEvictionRunsMillis = 60000;
	private Integer minEvictableIdleTimeMillis = 300000;
	private String validationQuery = "SELECT 1 FROM DUAL";
	private Boolean testWhileIdle = true;
	private Boolean testOnBorrow = false;
	private Boolean testOnReturn = false;
	private Boolean poolPreparedStatements = true;
	private Integer maxPoolPreparedStatementPerConnectionSize = 20;
	private String filters = "stat";
public void config(DruidDataSource dataSource) {
		Map<String, String> connectInfo = DBUtil.getConnectInfo(api);
		if (connectInfo != null) {
			url = connectInfo.get("url");
			username = connectInfo.get("username");
			password = connectInfo.get("password");
		}
		dataSource.setUrl(url);
		dataSource.setUsername(username);
		dataSource.setPassword(password);
		dataSource.setDriverClassName(driverClassName);
		dataSource.setInitialSize(initialSize); // 定义初始连接数
		dataSource.setMinIdle(minIdle); // 最小空闲
		dataSource.setMaxActive(maxActive); // 定义最大连接数
		dataSource.setMaxWait(maxWait); // 最长等待时间
		// 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
		dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
		// 配置一个连接在池中最小生存的时间,单位是毫秒
		dataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
		dataSource.setValidationQuery(validationQuery);
		dataSource.setTestWhileIdle(testWhileIdle);
		dataSource.setTestOnBorrow(testOnBorrow);
		dataSource.setTestOnReturn(testOnReturn);
		// 打开PSCache,并且指定每个连接上PSCache的大小
		dataSource.setPoolPreparedStatements(poolPreparedStatements);
		dataSource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
		try {
			dataSource.setFilters(filters);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
Getters.../Setters...
}

方式二:

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.sql.SQLException;
/**
 * <p>数据库数据源配置</p>
 * <p>说明:这个类中包含了许多默认配置,若这些配置符合您的情况,您可以不用管,若不符合,建议不要修改本类,建议直接在"application.yml"中配置即可</p>
 */
@Component
@ConfigurationProperties(prefix = "spring.datasource")
public class DruidProperties {
    private String url = "jdbc:mysql://127.0.0.1:3306/guns?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull";
    private String username = "root";
    private String password = "root";
    private String driverClassName = "com.mysql.jdbc.Driver";
    private Integer initialSize = 2;
    private Integer minIdle = 1;
    private Integer maxActive = 20;
    private Integer maxWait = 60000;
    private Integer timeBetweenEvictionRunsMillis = 60000;
    private Integer minEvictableIdleTimeMillis = 300000;
    private String validationQuery = "SELECT 'x'";
    private Boolean testWhileIdle = true;
    private Boolean testOnBorrow = false;
    private Boolean testOnReturn = false;
    private Boolean poolPreparedStatements = true;
    private Integer maxPoolPreparedStatementPerConnectionSize = 20;
    private String filters = "stat";
    public void config(DruidDataSource dataSource) {
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setDriverClassName(driverClassName);
        dataSource.setInitialSize(initialSize);     //定义初始连接数
        dataSource.setMinIdle(minIdle);             //最小空闲
        dataSource.setMaxActive(maxActive);         //定义最大连接数
        dataSource.setMaxWait(maxWait);             //最长等待时间
        // 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
        dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
        // 配置一个连接在池中最小生存的时间,单位是毫秒
        dataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
        //dataSource.setValidationQuery(validationQuery);
        dataSource.setTestWhileIdle(testWhileIdle);
        dataSource.setTestOnBorrow(testOnBorrow);
        dataSource.setTestOnReturn(testOnReturn);
        // 打开PSCache,并且指定每个连接上PSCache的大小
        dataSource.setPoolPreparedStatements(poolPreparedStatements);
        dataSource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
        try {
            dataSource.setFilters(filters);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
Getters.../Setters...
}




import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "spring.giveu-record")
public class GiveuRecordDataSourceProperties {
	private String driverClassName = "oracle.jdbc.driver.OracleDriver";
    private String url = "jdbc:mysql://127.0.0.1:3306/biz?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull";
    private String username = "root";
    private String password = "root";
    public void config(DruidDataSource dataSource) {
    	dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
}
Getters.../Setters...
}




import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.enums.Optimize;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.giveu.rqc.common.constant.DSEnum;
import com.giveu.rqc.config.properties.DruidProperties;
import com.giveu.rqc.config.properties.GiveuRecordDataSourceProperties;
import com.giveu.rqc.config.properties.GiveuSalesDataSourceProperties;
import com.giveu.rqc.core.mutidatesource.DynamicDataSource;
import com.giveu.rqc.core.util.HttpResult;
import com.giveu.rqc.core.util.HttpUtil;
import com.giveu.rqc.core.util.HttpUtils;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import java.sql.SQLException;
import java.util.HashMap;
/**
 * MybatisPlus配置
 */
@Configuration
@EnableTransactionManagement(order = 2)//由于引入多数据源,所以让spring事务的aop要在多数据源切换aop的后面
@MapperScan(basePackages = {"com.giveu.rqc.module.*.dao", "com.giveu.rqc.common.persistence.dao"})
public class MybatisPlusConfig {
    @Autowired
    DruidProperties druidProperties;
    @Autowired
    GiveuRecordDataSourceProperties giveuRecordProperties;
    /** 录音数据源
     */
    private DruidDataSource giveuRecordDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        druidProperties.config(dataSource);
        giveuRecordProperties.config(dataSource);
        return dataSource;
    }
    /** 当前系统的数据源
     */
    private DruidDataSource dataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        druidProperties.config(dataSource);
        return dataSource;
    }
    /** 单数据源连接池配置
     */
    @Bean
    @Primary
    @ConditionalOnProperty(prefix = "app", name = "muti-datasource-open", havingValue = "false")
    public DruidDataSource singleDatasource() {
        return dataSource();
    }
    /** 多数据源连接池配置
     */
    @Bean
    @Primary
    @ConditionalOnProperty(prefix = "app", name = "muti-datasource-open", havingValue = "true")
    public DynamicDataSource mutiDataSource() {
        DruidDataSource dataSource = dataSource();
        DruidDataSource giveuRecordDataSource = giveuRecordDataSource();
        try {
        	dataSource.init();
            giveuRecordDataSource.init();
        }catch (SQLException sql){
            sql.printStackTrace();
        }
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        HashMap<Object, Object> hashMap = new HashMap();
        hashMap.put(DSEnum.DATA_SOURCE, dataSource);
        hashMap.put(DSEnum.DATA_SOURCE_RECORD, giveuRecordDataSource);
        dynamicDataSource.setTargetDataSources(hashMap);
        dynamicDataSource.setDefaultTargetDataSource(dataSource);
        return dynamicDataSource;
    }
    /** mybatis-plus分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
    	PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
    	paginationInterceptor.setDynamicDataSource(true);
        //paginationInterceptor.setDialectType(DbType.MYSQL.getValue());
        paginationInterceptor.setOptimizeType(Optimize.JSQLPARSER.getOptimize());
        return paginationInterceptor;
    }
}




import javax.sql.DataSource;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MoreDataSourceConfig {
	@Bean
	@ConfigurationProperties(prefix = "spring.datasource")
	public DataSource baseDataSource() {
		return DataSourceBuilder.create().build();
	}
	@Bean
	@ConfigurationProperties(prefix="spring.giveu-record")
	public DataSource giveuRecordDataSource() {
		return DataSourceBuilder.create().build();
	}
	@Bean
	@ConfigurationProperties(prefix="spring.giveu-sales")
	public DataSource giveuSalesDataSource() {
		return DataSourceBuilder.create().build();
	}
}



import java.lang.annotation.*;
/**
 * 多数据源标识
 */
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD })
public @interface DataSource {
	String name() default "";
}



@Override
    @DataSource(name = DSEnum.DATA_SOURCE_RECORD)
    public List<ContractInfo> findContractInfo() {
        return mapper.select();
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值