spring boot1.x多数据源配置

perfect start 7月前 ⋅ 516 阅读

jpa多数据源配置

  • spring boot1.x

maven依赖

   <dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
		</dependency>
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jetty</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>springloaded</artifactId>
		</dependency>
		<dependency>
	        <groupId>org.springframework.boot</groupId>
	        <artifactId>spring-boot-starter-data-jpa</artifactId>
	    </dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.dataformat</groupId>
			<artifactId>jackson-dataformat-yaml</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-configuration-processor</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
		</dependency>
 </dependencies>

配置文件

server:
 port: 7373
mybatis:
 config-location: classpath:mybatis/mybatis.cfg.xml        # mybatis配置文件所在路径
 type-aliases-package: com.base.entities           # 所有Entity别名类所在包
 mapper-locations:
 - classpath:mybatis/mapper/**/*.xml                       # mapper映射文件
spring:
   profiles: dev
   primary:
     datasource:
       url: jdbc:mysql://mysql.host:3306/db3?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8&useSSL=false&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai
       username: zengyuwen
       password: 327523057zywZYW?
       driver-class-name: com.mysql.jdbc.Driver
   #secondary
   secondary:
     datasource:
       url: jdbc:mysql://mysql.host:3306/db1?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8&useSSL=false&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai
       username: username
       password: password
       driver-class-name: com.mysql.jdbc.Driver
   jpa:
     hibernate:
       primary-dialect: org.hibernate.dialect.MySQL5Dialect
       secondary-dialect: org.hibernate.dialect.MySQL5Dialect
     open-in-view: true
     show-sql: true    
   application:
     name: applicationName
   datasource:
     type: com.alibaba.druid.pool.DruidDataSource            # 当前数据源操作类型
     driver-class-name: org.gjt.mm.mysql.Driver              # mysql驱动包
     url: jdbc:mysql://mysql.host:3306/db2              # 数据库名称
     username: username
     password: password
     platform: mysql
     # 下面为连接池的补充设置,应用到上面所有数据源中
     # 初始化大小,最小,最大
     initialSize: 1
     minIdle: 3
     maxActive: 20
     # 配置获取连接等待超时的时间
     maxWait: 60000
     # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
     timeBetweenEvictionRunsMillis: 60000
     # 配置一个连接在池中最小生存的时间,单位是毫秒
     minEvictableIdleTimeMillis: 30000
     validationQuery: select 'x'
     testWhileIdle: true
     testOnBorrow: false
     testOnReturn: false
     # 打开PSCache,并且指定每个连接上PSCache的大小
     poolPreparedStatements: true
     maxPoolPreparedStatementPerConnectionSize: 20
     # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
     filters: stat,wall,slf4j
     # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
     connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
     # 合并多个DruidDataSource的监控数据
     #useGlobalDataSourceStat: true
     dbcp2:
       min-idle: 5                                           # 数据库连接池的最小维持连接数
       initial-size: 5                                       # 初始化连接数
       max-total: 5                                          # 最大连接数
       max-wait-millis: 200 

配置数据源

@Configuration
public class DataSourceConfig {
   // jpa数据源配置
   @Bean(name = "primaryDataSource")
   @Qualifier("primaryDataSource")
   @ConfigurationProperties(prefix="spring.primary.datasource")
   public DataSource primaryDataSource() {
       return DataSourceBuilder.create().build();
   }

   // jpa数据源配置
   @Bean(name = "secondaryDataSource")
   @Qualifier("secondaryDataSource")
   @Primary
   @ConfigurationProperties(prefix="spring.secondary.datasource")
   public DataSource secondaryDataSource() {
       return DataSourceBuilder.create().build();
   }

   // mybatis数据源配置
   @Bean(name = "myBatisDataSource")
   @Qualifier("myBatisDataSource")
   @ConfigurationProperties(prefix="spring.datasource")
   public DataSource myBatisDataSource() {
       return DataSourceBuilder.create().build();
   }
}

// 设置数据源1
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
       entityManagerFactoryRef = "entityManagerFactoryPrimary",
       transactionManagerRef = "transactionManagerPrimary",
       basePackages = {"com.base.jpa.dao.primary"})
public class PrimaryJpaDataSourceConfig {
	@Autowired
   private JpaProperties jpaProperties;

   @Autowired
   @Qualifier("primaryDataSource")
   private DataSource primaryDataSource;

   @Primary
   @Bean(name = "entityManagerPrimary")
   public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
       return entityManagerFactoryPrimary(builder).getObject().createEntityManager();
   }

   @Primary
   @Bean(name = "entityManagerFactoryPrimary")
   public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary(EntityManagerFactoryBuilder builder) {
       return builder
               .dataSource(primaryDataSource)
               .properties(getVendorProperties(primaryDataSource))
               .packages("com.base.jpa.entities.primary") //设置实体类所在位置
               .persistenceUnit("primaryPersistenceUnit")
               .build();
   }

   private Map<String, ?> getVendorProperties(DataSource dataSource) {
       return jpaProperties.getHibernateProperties(dataSource);
   }

   @Primary
   @Bean(name = "transactionManagerPrimary")
   public PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {
       return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject());
   }
}

// 设置数据源2
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
       entityManagerFactoryRef = "entityManagerFactorySecondary",
       transactionManagerRef = "transactionManagerSecondary",
       basePackages = {"com.base.jpa.dao.secondary"})
public class SecondaryJpaDataSourceConfig {
	@Autowired
   private JpaProperties jpaProperties;

   @Autowired
   @Qualifier("secondaryDataSource")
   private DataSource secondaryDataSource;

   @Bean(name = "entityManagerSecondary")
   public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
       return entityManagerFactorySecondary(builder).getObject().createEntityManager();
   }

   @Bean(name = "entityManagerFactorySecondary")
   public LocalContainerEntityManagerFactoryBean entityManagerFactorySecondary(EntityManagerFactoryBuilder builder) {
       return builder
               .dataSource(secondaryDataSource)
               .properties(getVendorProperties(secondaryDataSource))
               .packages("com.base.jpa.entities.secondary") //设置实体类所在位置
               .persistenceUnit("primaryPersistenceUnit")
               .build();
   }


   private Map<String, ?> getVendorProperties(DataSource dataSource) {
       return jpaProperties.getHibernateProperties(dataSource);
   }

   @Bean(name = "transactionManagerSecondary")
   PlatformTransactionManager transactionManagerSecondary(EntityManagerFactoryBuilder builder) {
       return new JpaTransactionManager(entityManagerFactorySecondary(builder).getObject());
   }

}

// 设置mybatis数据源
@Configuration
@MapperScan(basePackages = {MyBatisDataSourceConfig.MAPPER_PACKAGE})
public class MyBatisDataSourceConfig {
	
	@Autowired
   @Qualifier("myBatisDataSource")
   private DataSource dataSourceConfig;
	
	public static final String MAPPER_PACKAGE = "com.base.dao.mybatis";
	 
   public static final String MAPPER_XML_PACKAGE = "classpath:mybatis/mapper/*.xml";

   public static final String MYBATIS_BEAN_PACKAGE = "com.base.entities.mybatis";

	
	@Bean(name = "sqlSessionFactory")
   public SqlSessionFactory sqlSessionFactory() throws Exception {
       SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
       sqlSessionFactoryBean.setDataSource(dataSourceConfig);

       //设置扫描 mybatis-config.xml
       sqlSessionFactoryBean.setConfigLocation(null);

       //设置扫描mapper.xml
       PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
       Resource[] resources = resolver.getResources(MAPPER_XML_PACKAGE);
       sqlSessionFactoryBean.setMapperLocations(resources);

       //设置扫描实体类
       sqlSessionFactoryBean.setTypeAliasesPackage(MYBATIS_BEAN_PACKAGE);

       return sqlSessionFactoryBean.getObject();
   }


   @Primary
   @Bean(name = "sqlSessionTemplate")
   public SqlSessionTemplate popSqlSessionTemplate(@Qualifier("sqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
       return new SqlSessionTemplate(sqlSessionFactory);
   }

   @Primary
   @Bean(name = "transactionManager")
   public DataSourceTransactionManager transactionManager() {
       return new DataSourceTransactionManager(dataSourceConfig);
   }
}

全部评论: 0

    我有话说: