多数据源应用场景
使用mabatis框架+druid数据源
当业务量达到一定量的时候,DataBase需要合理配置数据库资源,即把高频访问的数据放在主库上,低频访问的数据放在从库上,从而达到服务器CPU的合理应用。
多数据源应用
准备两个数据库,taotao和pms
新建springboot工程
选择web与mybatis
pom文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.enowsh</groupId>
<artifactId>boot-mybatis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>boot-mybatis</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.9</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.5</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>3.4.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
工程结构
application.properties配置文件
#多个数据源配置
#master数据源配置
master.datasource.url=jdbc:mysql://localhost:3306/pms?characterEncoding=utf-8
master.datasource.username=root
master.datasource.password=wyx2020
master.datasource.driverClassName=com.mysql.jdbc.Driver
#cluster数据源配置
cluster.datasource.url=jdbc:mysql://localhost:3306/taotao?characterEncoding=utf-8
cluster.datasource.username=root
cluster.datasource.password=wyx2020
cluster.datasource.driverClassName=com.mysql.jdbc.Driver
主从数据源的配置-使用java代码
主数据源配置
package com.enowsh.boot_mybatis.config.dataSource;
import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
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 javax.sql.DataSource;
import java.io.IOException;
/**
* @author:wong
*/
@Configuration
//扫描mapper接口包
@MapperScan(basePackages = "com.enowsh.boot_mybatis.mapper.master",sqlSessionFactoryRef = "masterSqlSessionFactory")
public class MasterDataSourceConfig {
@Value("${master.datasource.url}")
private String masterDataSourceUrl;
@Value("${master.datasource.username}")
private String masterDatasourceUsername;
@Value("${master.datasource.password}")
private String masterDatasourcePassword;
@Value("${master.datasource.driverClassName}")
private String masterDatasourceDriverClassName;
//定义dataSource的bean
@Bean(name = "masterDataSource")
@Primary //primary注解标志如果有多类同类bean候选,则优先考虑该bean,即主数据源
public DataSource masterDataSource(){
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUsername(masterDatasourceUsername);
dataSource.setPassword(masterDatasourcePassword);
dataSource.setDriverClassName(masterDatasourceDriverClassName);
dataSource.setUrl(masterDataSourceUrl);
return dataSource;
}
//定义sqlSessionFactory的bean
@Bean(name = "masterSqlSessionFactory")
@Primary
//使用@Qualifier注解同样是注入bean,但该注入方式是查找bean的name
//@Autowired注入是根据bean的类型来查找bean注入
public SqlSessionFactory masterSqlSessionFactory(@Qualifier("masterDataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
//扫描mapper.xml文件
sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/master/*.xml"));
return sqlSessionFactoryBean.getObject();
}
}
- 其中类头上需要扫描mapper的接口包,将接口bean注入到容器
- @Primary注解:如果有多个同类型的bean配置,则优先配置该bean,即主数据源的bean
- @Qualifier("beanName")注解:与@Autowired不同的是,Qualifer是根据bean的name来查找bean,Autowired是根据类型查找,由于有多个数据源的bean,所以若使用Autowired则会查找到多个同类型的bean,不能识别,这时,需要使用Qualifer根据bean的名称注入
- sqlSessionFactoryBean设置mapper的Location是指设置mapper.xml文件的location
从数据源参考主数据源
package com.enowsh.boot_mybatis.config.dataSource;
import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
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 javax.sql.DataSource;
import java.io.IOException;
/**
* @author:wong
*/
@Configuration
//扫描mapper接口包
@MapperScan(basePackages = "com.enowsh.boot_mybatis.mapper.cluster",sqlSessionFactoryRef = "clusterSqlSessionFactory")
public class ClusterDataSourceConfig {
@Value("${cluster.datasource.url}")
private String clusterDataSourceUrl;
@Value("${cluster.datasource.username}")
private String clusterDatasourceUsername;
@Value("${cluster.datasource.password}")
private String clusterDatasourcePassword;
@Value("${cluster.datasource.driverClassName}")
private String clusterDatasourceDriverClassName;
//定义dataSource的bean
@Bean(name = "clusterDataSource")
public DataSource clusterDataSource(){
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUsername(clusterDatasourceUsername);
dataSource.setPassword(clusterDatasourcePassword);
dataSource.setDriverClassName(clusterDatasourceDriverClassName);
dataSource.setUrl(clusterDataSourceUrl);
return dataSource;
}
//定义sqlSessionFactory的bean
@Bean(name = "clusterSqlSessionFactory")
//使用@Qualifier注解同样是注入bean,但该注入方式是查找bean的name
//@Autowired注入是根据bean的类型来查找bean注入
public SqlSessionFactory clusterSqlSessionFactory(@Qualifier("clusterDataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
//扫描mapper.xml文件
sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/cluster/*.xml"));
return sqlSessionFactoryBean.getObject();
}
}
编写service程序测试
package com.enowsh.boot_mybatis.service.impl;
import com.enowsh.boot_mybatis.mapper.cluster.TbUserMapper;
import com.enowsh.boot_mybatis.mapper.master.PmsUserMapper;
import com.enowsh.boot_mybatis.pojo.PmsResult;
import com.enowsh.boot_mybatis.pojo.PmsUser;
import com.enowsh.boot_mybatis.pojo.TbUser;
import com.enowsh.boot_mybatis.service.MutiDataSourceService;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
/**
* @author:wong
*/
@Service
@Transactional
public class MutiDataSourceServiceImpl implements MutiDataSourceService {
@Autowired
private TbUserMapper tbUserMapper;
@Autowired
private PmsUserMapper pmsUserMapper;
@Override
public PmsResult findDifferentUser(long pmsId, long taotaoId) {
PmsUser pmsUser = pmsUserMapper.selectByPrimaryKey(pmsId);
TbUser tbUser = tbUserMapper.selectByPrimaryKey(taotaoId);
if (pmsUser==null||tbUser==null)
return PmsResult.build(400,"用户查询失败");
List list=new ArrayList();
list.add(pmsUser);
list.add(tbUser);
return PmsResult.ok(list);
}
}
controller程序
package com.enowsh.boot_mybatis.controller;
import com.enowsh.boot_mybatis.pojo.PmsResult;
import com.enowsh.boot_mybatis.service.MutiDataSourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.security.PermitAll;
/**
* @author:wong
*/
@Controller
public class MutiDataSourceController {
@Autowired
private MutiDataSourceService mutiDataSourceService;
@RequestMapping("/muti/{taotaoId}/{pmsId}")
@ResponseBody
public PmsResult findUser(@PathVariable long taotaoId, @PathVariable long pmsId){
PmsResult pmsResult = mutiDataSourceService.findDifferentUser(pmsId, taotaoId);
return pmsResult;
}
}